當前位置: 首頁>>代碼示例>>Golang>>正文


Golang gouuid.ParseHex函數代碼示例

本文整理匯總了Golang中github.com/nu7hatch/gouuid.ParseHex函數的典型用法代碼示例。如果您正苦於以下問題:Golang ParseHex函數的具體用法?Golang ParseHex怎麽用?Golang ParseHex使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了ParseHex函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: NewHttpStartStop

func NewHttpStartStop(req *http.Request, statusCode int, contentLength int64, peerType events.PeerType, requestId *uuid.UUID) *events.HttpStartStop {
	now := proto.Int64(time.Now().UnixNano())
	httpStartStop := &events.HttpStartStop{
		StartTimestamp: now,
		StopTimestamp:  now,
		RequestId:      NewUUID(requestId),
		PeerType:       &peerType,
		Method:         events.Method(events.Method_value[req.Method]).Enum(),
		Uri:            proto.String(fmt.Sprintf("%s://%s%s", scheme(req), req.Host, req.URL.Path)),
		RemoteAddress:  proto.String(req.RemoteAddr),
		UserAgent:      proto.String(req.UserAgent()),
		StatusCode:     proto.Int(statusCode),
		ContentLength:  proto.Int64(contentLength),
	}

	if applicationId, err := uuid.ParseHex(req.Header.Get("X-CF-ApplicationID")); err == nil {
		httpStartStop.ApplicationId = NewUUID(applicationId)
	}

	if instanceIndex, err := strconv.Atoi(req.Header.Get("X-CF-InstanceIndex")); err == nil {
		httpStartStop.InstanceIndex = proto.Int(instanceIndex)
	}

	if instanceId := req.Header.Get("X-CF-InstanceID"); instanceId != "" {
		httpStartStop.InstanceId = proto.String(instanceId)
	}

	allForwards := req.Header[http.CanonicalHeaderKey("X-Forwarded-For")]
	for _, forwarded := range allForwards {
		httpStartStop.Forwarded = append(httpStartStop.Forwarded, parseXForwarded(forwarded)...)
	}

	return httpStartStop
}
開發者ID:cloudfoundry,項目名稱:v3-cli-plugin,代碼行數:34,代碼來源:factories.go

示例2: NewHttpStart

func NewHttpStart(req *http.Request, peerType events.PeerType, requestId *uuid.UUID) *events.HttpStart {
	httpStart := &events.HttpStart{
		Timestamp:     proto.Int64(time.Now().UnixNano()),
		RequestId:     NewUUID(requestId),
		PeerType:      &peerType,
		Method:        events.HttpStart_Method(events.HttpStart_Method_value[req.Method]).Enum(),
		Uri:           proto.String(fmt.Sprintf("%s%s", req.Host, req.URL.Path)),
		RemoteAddress: proto.String(req.RemoteAddr),
		UserAgent:     proto.String(req.UserAgent()),
	}

	if applicationId, err := uuid.ParseHex(req.Header.Get("X-CF-ApplicationID")); err == nil {
		httpStart.ApplicationId = NewUUID(applicationId)
	}

	if instanceIndex, err := strconv.Atoi(req.Header.Get("X-CF-InstanceIndex")); err == nil {
		httpStart.InstanceIndex = proto.Int(instanceIndex)
	}

	if instanceId := req.Header.Get("X-CF-InstanceID"); instanceId != "" {
		httpStart.InstanceId = &instanceId
	}

	return httpStart
}
開發者ID:KeyOfSpectator,項目名稱:gorouter,代碼行數:25,代碼來源:factories.go

示例3: PushMsg

func (this *UdpSessionList) PushMsg(did int64, msg []byte) error {
	sid, err := GetDeviceSid(did)
	if err != nil {
		return fmt.Errorf("[udp:err] get session of device [%d] error: %v", did, err)
	}

	locker := NewDeviceSessionLocker(sid)
	err = locker.Lock()
	if err != nil {
		return fmt.Errorf("lock session id [%s] failed: %v", sid, err)
	}
	defer locker.Unlock()

	i, err := uuid.ParseHex(sid)
	if err != nil {
		return fmt.Errorf("wrong session id format: %v", err)
	}
	sess, err := this.GetSession(i)
	if err != nil {
		return fmt.Errorf("get session %s error: %v", sid, err)
	}
	sess.Sidx++

	binary.LittleEndian.PutUint16(msg[2:4], sess.Sidx)
	copy(msg[FrameHeaderLen:FrameHeaderLen+kSidLen], i[:])
	//hcIndex := FrameHeaderLen + kSidLen + FrameHeaderLen + kHeaderCheckPosInDataHeader
	//glog.Infoln("PushMsg----------sess:",	sess)
	//msg[hcIndex] = msgs.ChecksumHeader(msg, hcIndex)
	//glog.Infoln("PushMsg:",did,len(msg),msg,hcIndex)
	this.server.Send(sess.Addr, msg)
	this.SaveSession(i, sess)
	return nil
}
開發者ID:ljvblfz,項目名稱:slot-golang,代碼行數:33,代碼來源:udp_session.go

示例4: RoundTrip

/*
Wraps the RoundTrip function of the given RoundTripper.
Will provide accounting metrics for the http.Request / http.Response life-cycle
Callers of RoundTrip are responsible for setting the ‘X-CF-RequestID’ field in the request header if they have one.
Callers are also responsible for setting the ‘X-CF-ApplicationID’ and ‘X-CF-InstanceIndex’ fields in the request header if they are known.
*/
func (irt *instrumentedRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	requestId, err := GenerateUuid()
	if err != nil {
		log.Printf("failed to generated request ID: %v\n", err)
		requestId = &uuid.UUID{}
	}

	startTime := time.Now()
	parentRequestId := req.Header.Get("X-CF-RequestID")
	req.Header.Set("X-CF-RequestID", requestId.String())

	resp, roundTripErr := irt.roundTripper.RoundTrip(req)

	var statusCode int
	var contentLength int64
	if roundTripErr == nil {
		statusCode = resp.StatusCode
		contentLength = resp.ContentLength
	}

	httpStartStop := factories.NewHttpStartStop(req, statusCode, contentLength, events.PeerType_Client, requestId)
	if parentRequestId != "" {
		if id, err := uuid.ParseHex(parentRequestId); err == nil {
			httpStartStop.ParentRequestId = factories.NewUUID(id)
		}
	}
	httpStartStop.StartTimestamp = proto.Int64(startTime.UnixNano())

	err = irt.emitter.Emit(httpStartStop)
	if err != nil {
		log.Printf("failed to emit startstop event: %v\n", err)
	}

	return resp, roundTripErr
}
開發者ID:st3v,項目名稱:arp-watch,代碼行數:41,代碼來源:instrumented_round_tripper.go

示例5: PushCommonMsg

func (this *UdpSessionList) PushCommonMsg(msgId uint16, did int64, msgBody []byte) error {
	msg := msgs.NewMsg(msgBody, nil)
	msg.FrameHeader.Opcode = 2
	msg.DataHeader.MsgId = msgId
	msg.FrameHeader.DstId = did

	sid, err := GetDeviceSid(did)
	if err != nil {
		return fmt.Errorf("[udp:err] get session of device [%d] error: %v", did, err)
	}

	locker := NewDeviceSessionLocker(sid)
	err = locker.Lock()
	if err != nil {
		return fmt.Errorf("[udp:err] lock session id [%s] failed: %v", sid, err)
	}
	defer locker.Unlock()

	i, err := uuid.ParseHex(sid)
	if err != nil {
		return fmt.Errorf("[udp:err] wrong session id format: %v", err)
	}
	sess, err := this.GetSession(i)
	if err != nil {
		return fmt.Errorf("[udp:err] get session %s error: %v", sid, err)
	}
	sess.Sidx++
	msg.FrameHeader.Sequence = sess.Sidx
	msgBytes := msg.MarshalBytes()
	this.server.Send(sess.Addr, msgBytes)

	this.SaveSession(i, sess)
	return nil
}
開發者ID:ljvblfz,項目名稱:slot-golang,代碼行數:34,代碼來源:udp_session.go

示例6: ServeHTTP

/*
Wraps the given http.Handler ServerHTTP function
Will provide accounting metrics for the http.Request / http.Response life-cycle
*/
func (ih *instrumentedHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	requestId, err := uuid.ParseHex(req.Header.Get("X-Vcap-Request-Id"))
	if err != nil {
		requestId, err = GenerateUuid()
		if err != nil {
			log.Printf("failed to generated request ID: %v\n", err)
			requestId = &uuid.UUID{}
		}
		req.Header.Set("X-Vcap-Request-Id", requestId.String())
	}
	rw.Header().Set("X-Vcap-Request-Id", requestId.String())

	startTime := time.Now()

	instrumentedWriter := &instrumentedResponseWriter{writer: rw, statusCode: 200}
	ih.handler.ServeHTTP(instrumentedWriter, req)

	startStopEvent := factories.NewHttpStartStop(req, instrumentedWriter.statusCode, instrumentedWriter.contentLength, events.PeerType_Server, requestId)
	startStopEvent.StartTimestamp = proto.Int64(startTime.UnixNano())

	err = ih.emitter.Emit(startStopEvent)
	if err != nil {
		log.Printf("failed to emit startstop event: %v\n", err)
	}
}
開發者ID:sunatthegilddotcom,項目名稱:gorouter,代碼行數:29,代碼來源:instrumented_handler.go

示例7: main

func main() {
	u, err := uuid.ParseHex("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(u)
}
開發者ID:robertsturner52,項目名稱:CIT90,代碼行數:8,代碼來源:main.go

示例8: main

func main() {
	fmt.Print("hello, world\n")
	ID, err := uuid.ParseHex("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
	fmt.Println(ID)
	if err != nil {
		fmt.Println(err)
	}

}
開發者ID:jhburns21,項目名稱:CSCI-191T,代碼行數:9,代碼來源:hello.go

示例9: UpdateIds

func (this *UdpSessionList) UpdateIds(deviceId int64, userId int64, bindType bool) {
	sid, err := GetDeviceSid(deviceId)
	if err != nil {
		glog.Errorf("get session of device [%d] error: %v", deviceId, err)
		return
	}

	locker := NewDeviceSessionLocker(sid)
	err = locker.Lock()
	if err != nil {
		glog.Errorf("lock session id [%s] failed: %v", sid, err)
		return
	}
	defer locker.Unlock()

	i, err := uuid.ParseHex(sid)
	if err != nil {
		glog.Errorf("wrong session id format: %v", err)
		return
	}
	sess, err := this.GetSession(i)
	if err != nil {
		glog.Errorf("get session %s error: %v", sid, err)
		return
	}
	if bindType {
		// 綁定
		sess.BindedUsers = append(sess.BindedUsers, userId)
		glog.Infof("[bind|bind] deviceId %d add userId %d", deviceId, userId)

	} else {
		// 解綁
		for k, v := range sess.BindedUsers {
			if v != userId {
				continue
			}
			lastIndex := len(sess.BindedUsers) - 1
			sess.BindedUsers[k] = sess.BindedUsers[lastIndex]
			sess.BindedUsers = sess.BindedUsers[:lastIndex]
			glog.Infof("[bind|unbind] deviceId %d remove userId %d", deviceId, userId)
			break
		}
	}
	this.SaveSession(i, sess)

	go func() {
		mids := TransId(userId)
		if bindType {
			GMsgBusManager.NotifyBindedIdChanged(deviceId, mids, nil)
		} else {
			GMsgBusManager.NotifyBindedIdChanged(deviceId, nil, mids)
		}
	}()
}
開發者ID:ljvblfz,項目名稱:slot-golang,代碼行數:54,代碼來源:udp_session.go

示例10: NewHttpStop

func NewHttpStop(req *http.Request, statusCode int, contentLength int64, peerType events.PeerType, requestId *uuid.UUID) *events.HttpStop {
	httpStop := &events.HttpStop{
		Timestamp:     proto.Int64(time.Now().UnixNano()),
		Uri:           proto.String(fmt.Sprintf("%s%s", req.Host, req.URL.Path)),
		RequestId:     NewUUID(requestId),
		PeerType:      &peerType,
		StatusCode:    proto.Int(statusCode),
		ContentLength: proto.Int64(contentLength),
	}

	if applicationId, err := uuid.ParseHex(req.Header.Get("X-CF-ApplicationID")); err == nil {
		httpStop.ApplicationId = NewUUID(applicationId)
	}

	return httpStop
}
開發者ID:KeyOfSpectator,項目名稱:gorouter,代碼行數:16,代碼來源:factories.go

示例11: EncryptToken

func (csi *ClearSessionId) EncryptToken() (SessionId string, err error) {
	// validate the session token by parsing it
	_, err = uuid.ParseHex(csi.SessionToken)
	if err != nil {
		err = fmt.Errorf("SessionToken (%s) is not a UUID", csi.SessionToken)
		return "", err
	}

	if csi.Salt == "" {
		err = fmt.Errorf("Salt is missing")
		return "", err
	}

	if len(csi.Salt) != 64 {
		err = fmt.Errorf("Salt must be 32 bytes but was %d bytes", len(csi.Salt)/2)
		return "", err
	}

	// scrypt is slow and good for passwords
	// sha512 is faster and good for sessions
	saltBytes, err := hex.DecodeString(csi.Salt)
	if err != nil {
		glog.Errorf("Undecodable salt (%s)", csi.Salt)
		return "", err
	}

	combined := make([]byte, 64+32+36)
	_ = copy(combined[0:64], Conf.ServerKey)
	_ = copy(combined[64:96], saltBytes)
	_ = copy(combined[96:], []byte(csi.SessionToken))

	sum512 := sha512.Sum512(combined)

	SessionId = hex.EncodeToString(sum512[:])

	return SessionId, nil
}
開發者ID:Grant-Murray,項目名稱:session,代碼行數:37,代碼來源:session_model.go

示例12: RoundTrip

/*
Wraps the RoundTrip function of the given RoundTripper.
Will provide accounting metrics for the http.Request / http.Response life-cycle
Callers of RoundTrip are responsible for setting the ‘X-CF-RequestID’ field in the request header if they have one.
Callers are also responsible for setting the ‘X-CF-ApplicationID’ and ‘X-CF-InstanceIndex’ fields in the request header if they are known.
*/
func (irt *instrumentedRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	requestId, err := GenerateUuid()
	if err != nil {
		log.Printf("failed to generated request ID: %v\n", err)
		requestId = &uuid.UUID{}
	}

	httpStart := factories.NewHttpStart(req, events.PeerType_Client, requestId)

	parentRequestId, err := uuid.ParseHex(req.Header.Get("X-CF-RequestID"))
	if err == nil {
		httpStart.ParentRequestId = factories.NewUUID(parentRequestId)
	}

	req.Header.Set("X-CF-RequestID", requestId.String())

	err = irt.emitter.Emit(httpStart)
	if err != nil {
		log.Printf("failed to emit start event: %v\n", err)
	}

	resp, roundTripErr := irt.roundTripper.RoundTrip(req)

	var httpStop *events.HttpStop
	if roundTripErr != nil {
		httpStop = factories.NewHttpStop(req, 0, 0, events.PeerType_Client, requestId)
	} else {
		httpStop = factories.NewHttpStop(req, resp.StatusCode, resp.ContentLength, events.PeerType_Client, requestId)
	}

	err = irt.emitter.Emit(httpStop)
	if err != nil {
		log.Printf("failed to emit stop event: %v\n", err)
	}

	return resp, roundTripErr
}
開發者ID:johannespetzold,項目名稱:gorouter,代碼行數:43,代碼來源:instrumented_round_tripper.go

示例13: RoundTrip

/*
RoundTrip wraps the RoundTrip function of the given RoundTripper.
Will provide accounting metrics for the http.Request / http.Response life-cycle
Callers of RoundTrip are responsible for setting the ‘X-Vcap-Request-Id’ field in the request header if they have one.
Callers are also responsible for setting the ‘X-CF-ApplicationID’ and ‘X-CF-InstanceIndex’ fields in the request header if they are known.
*/
func (irt *instrumentedRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	startTime := time.Now()
	requestId := req.Header.Get("X-Vcap-Request-Id")
	if requestId == "" {
		requestIdGuid, err := uuid.NewV4()
		if err != nil {
			return nil, err
		}
		requestId = requestIdGuid.String()
	}

	req.Header.Set("X-Vcap-Request-Id", requestId)

	resp, roundTripErr := irt.roundTripper.RoundTrip(req)

	var statusCode int
	var contentLength int64
	if roundTripErr == nil {
		statusCode = resp.StatusCode
		contentLength = resp.ContentLength
	}

	id, err := uuid.ParseHex(requestId)
	if err != nil {
		return nil, err
	}

	httpStartStop := factories.NewHttpStartStop(req, statusCode, contentLength, events.PeerType_Client, id)
	httpStartStop.StartTimestamp = proto.Int64(startTime.UnixNano())

	err = irt.emitter.Emit(httpStartStop)
	if err != nil {
		log.Printf("failed to emit startstop event: %v\n", err)
	}

	return resp, roundTripErr
}
開發者ID:Reejoshi,項目名稱:cli,代碼行數:43,代碼來源:instrumented_round_tripper.go

示例14: GetDeviceAddr

func (this *UdpSessionList) GetDeviceAddr(id int64) (string, error) {
	glog.Infoln("GetDeviceAddr ", id)
	sid, err := GetDeviceSid(id)
	if err != nil {
		return "", fmt.Errorf("get session of device [%d] error: %v", id, err)
	}

	locker := NewDeviceSessionLocker(sid)
	err = locker.Lock()
	if err != nil {
		return "", fmt.Errorf("lock session id [%s] failed: %v", sid, err)
	}
	defer locker.Unlock()

	i, err := uuid.ParseHex(sid)
	if err != nil {
		return "", fmt.Errorf("wrong session id format: %v", err)
	}
	sess, err := this.GetSession(i)
	if err != nil {
		return "", fmt.Errorf("get session %s error: %v", sid, err)
	}
	return sess.Addr.String(), nil
}
開發者ID:ljvblfz,項目名稱:slot-golang,代碼行數:24,代碼來源:udp_session.go

示例15: useResetToken

// useResetToken creates a login session and returns the session cookies so that a user can change their password, for valid reset tokens only (also verifies email address)
func useResetToken(rw http.ResponseWriter, req *http.Request) {
	localPrefix := fmt.Sprintf("useReset-%s:", context.Get(req, RequestLogIdKey))
	if glog.V(2) {
		glog.Infof("%s handling begins: %s (%d bytes)", localPrefix, req.URL, req.ContentLength)
	}

	vars := mux.Vars(req)
	inEmailAddr := strings.TrimSpace(strings.ToLower(vars["EmailAddr"]))
	inResetToken := vars["Token"]

	response := DefaultLoginResponse(localPrefix)
	response.ValidationResult.Message = "Reset failed"

	var err error

	defer func() {
		// encode response to json and write the response
		setSessionCookies(rw, response)
		enc := json.NewEncoder(rw)
		rw.Header().Add("Content-Type", "application/json")
		err = enc.Encode(response)
		if err != nil {
			glog.Errorf("%s Failed to encode response into json", localPrefix)
		}

		if glog.V(2) {
			glog.Infof("%s handling ends with result message: %s", localPrefix, response.ValidationResult.Message)
		}
		glog.Flush()
	}()

	// check if email matches the pattern
	if isMatched, _ := regexp.MatchString(emailRegex, inEmailAddr); !isMatched {
		response.ValidationResult.PropInError = "EmailAddr"
		response.ValidationResult.PropErrorMsg = "Not a valid email address"
		return
	}

	// validate the token by parsing it
	_, err = uuid.ParseHex(inResetToken)
	if err != nil {
		response.ValidationResult.PropInError = "ResetToken"
		response.ValidationResult.PropErrorMsg = "Not a valid reset token"
		return
	}

	// fetch the user
	userRow, err := SelectUser(inEmailAddr)
	if err != nil {
		if glog.V(2) {
			glog.Infof("%s SelectUser err: %s", localPrefix, err)
		}
		return
	}

	// token in db must be there (obviously)
	if userRow.reset_token == "" {
		if glog.V(2) {
			glog.Infof("%s No reset token in database", localPrefix)
		}
		return
	}

	// token must be active not expired (if reset_token is not blank then reset_expires should
	//   be a valid timestamp, so no need to check that)
	if userRow.reset_expires.Before(time.Now()) {
		if glog.V(2) {
			glog.Infof("%s Reset token is expired", localPrefix)
		}
		return
	}

	// Check if login allowed
	if !userRow.login_allowed {
		if glog.V(2) {
			glog.Infof("%s login_allowed is false", localPrefix)
		}
		return
	}

	// tokens must match
	cryptToken, err := encryptResetToken(inResetToken, userRow.SysUserId)
	if err != nil {
		if glog.V(2) {
			glog.Infof("%s encryptResetToken err: %s", localPrefix, err)
		}
		return
	}

	if cryptToken != userRow.reset_token {
		if glog.V(2) {
			glog.Infof("%s Given token does not match the token on record", localPrefix)
		}
		return
	}

	if err = userRow.RemoveResetToken(); err != nil {
		if glog.V(2) {
			glog.Infof("%s RemoveResetToken err: %s", localPrefix, err)
//.........這裏部分代碼省略.........
開發者ID:Grant-Murray,項目名稱:session,代碼行數:101,代碼來源:session.go


注:本文中的github.com/nu7hatch/gouuid.ParseHex函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。