当前位置: 首页>>代码示例>>Golang>>正文


Golang Context.Value方法代码示例

本文整理汇总了Golang中golang.org/x/net/context.Context.Value方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Value方法的具体用法?Golang Context.Value怎么用?Golang Context.Value使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在golang.org/x/net/context.Context的用法示例。


在下文中一共展示了Context.Value方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ContextJWT

// ContextJWT retrieves the JWT token from a `context` that went through our security
// middleware.
func ContextJWT(ctx context.Context) *jwt.Token {
	token, ok := ctx.Value(jwtKey).(*jwt.Token)
	if !ok {
		return nil
	}
	return token
}
开发者ID:ajoulie,项目名称:goa,代码行数:9,代码来源:jwt.go

示例2: Path

/*
Path returns the path that the Goji router uses to perform the PathPrefix
optimization. While this function does not distinguish between the absence of a
path and an empty path, Goji will automatically extract a path from the request
if none is present.

By convention, paths are stored in their escaped form (i.e., the value returned
by net/url.URL.EscapedPath, and not URL.Path) to ensure that Patterns have as
much discretion as possible (e.g., to behave differently for '/' and '%2f').
*/
func Path(ctx context.Context) string {
	pi := ctx.Value(internal.Path)
	if pi == nil {
		return ""
	}
	return pi.(string)
}
开发者ID:stellar,项目名称:bridge-server,代码行数:17,代码来源:pattern.go

示例3: appUserToken

func appUserToken(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	// get t from ctx
	t := ctx.Value("test").(*testing.T)

	// Test whether the user is authenticated
	if r.Header.Get("X-Identity-Status") != "Confirmed" {
		t.Errorf("At the app, the user token should already be confirmed, got: %v", r.Header.Get("X-Identity-Status"))
	}
	if r.Header.Get("X-User-Id") != "10a2e6e717a245d9acad3e5f97aeca3d" {
		t.Errorf("At the app, the user should be 10a2e6e717a245d9acad3e5f97aeca3d, got: %v", r.Header.Get("X-User-Id"))
	}
	if r.Header.Get("X-User-Name") != "testuser" {
		t.Errorf("At the app, the user should be testuser, got: %v", r.Header.Get("X-User-Name"))
	}
	if r.Header.Get("X-Domain-Id") != "default" {
		t.Errorf("At the app, the user should be default, got: %v", r.Header.Get("X-Domain-Id"))
	}

	// Test ctx's Context Parameter with key "UserAccessInfo"
	value := router.MiddlewareParam(ctx, UserAccessInfoKey)
	if value == nil {
		t.Error("ctx should contain user access info")
	} else {
		access, ok := value.(*client.AccessInfo)
		if !ok {
			t.Error("it is not accessinfo, what is it?")
		}
		if access.Token != "usertoken" || access.TokenInfo.User.Domain.Name != "Default" {
			t.Error("ctx's accessinfo contains wrong information")
		}
	}

	w.Write([]byte("Test success!"))
}
开发者ID:heartsg,项目名称:dasea,代码行数:34,代码来源:authtoken_test.go

示例4: deleteNote

func deleteNote(ctx context.Context, req interface{}) (interface{}, *ErrorResponse) {
	db := ctx.Value("db").(*gorp.DbMap)
	noteId, err := strconv.Atoi(kami.Param(ctx, "noteId"))

	if err != nil {
		return nil, &ErrorResponse{
			http.StatusBadRequest,
			fmt.Sprintf("Invalid note id format: %v", err),
		}
	}

	note := new(model.Note)
	err = db.SelectOne(note, "select * from notes where id = ?", noteId)
	if err != nil {
		return nil, &ErrorResponse{
			http.StatusBadRequest,
			fmt.Sprintf("Query failed: %v", err),
		}
	}

	if _, err := db.Delete(note); err != nil {
		return nil, &ErrorResponse{
			http.StatusInternalServerError,
			fmt.Sprintf("Delete failed: %v", err),
		}
	}

	return nil, nil
}
开发者ID:keichi,项目名称:scribble,代码行数:29,代码来源:note_handler.go

示例5: EffectiveCallerIDFromContext

// EffectiveCallerIDFromContext returns the EffectiveCallerID(vtpb.CallerID)
// stored in the Context, if any
func EffectiveCallerIDFromContext(ctx context.Context) *vtpb.CallerID {
	ef, ok := ctx.Value(effectiveCallerIDKey).(*vtpb.CallerID)
	if ok && ef != nil {
		return ef
	}
	return nil
}
开发者ID:tjyang,项目名称:vitess,代码行数:9,代码来源:callerid.go

示例6: register

func register(ctx context.Context, req interface{}) (interface{}, *ErrorResponse) {
	input := req.(*registerRequest)
	dbMap := ctx.Value("db").(*gorp.DbMap)

	if input.Username == "" {
		return nil, &ErrorResponse{http.StatusBadRequest, "username is empty"}
	}

	if input.Password == "" {
		return nil, &ErrorResponse{http.StatusBadRequest, "password is empty"}
	}

	count, err := dbMap.SelectInt("select count(id) from users where username = ?", input.Username)
	if err != nil {
		return nil, &ErrorResponse{http.StatusInternalServerError, err.Error()}
	}
	if count > 0 {
		return nil, &ErrorResponse{http.StatusBadRequest, "user exists"}
	}

	user := model.User{
		0,
		input.Username,
		auth.HashPassword(input.Username, input.Password),
		input.Email,
		time.Now().UnixNano(),
		time.Now().UnixNano(),
	}

	if err := dbMap.Insert(&user); err != nil {
		return nil, &ErrorResponse{http.StatusInternalServerError, err.Error()}
	}

	return map[string]string{"message": "user created"}, nil
}
开发者ID:keichi,项目名称:scribble,代码行数:35,代码来源:auth_handler.go

示例7: Load

// Load will return the current session, creating one if necessary. This will
// fail if a store wasn't installed with HandlerWithStore somewhere up the
// call chain.
func Load(ctx context.Context, namespace string) (*Session, error) {
	rc, ok := ctx.Value(reqCtxKey).(*reqCtx)
	if !ok {
		return nil, errors.ProgrammerError.New(
			"no session store handler wrapper installed")
	}
	if rc.cache != nil {
		if session, exists := rc.cache[namespace]; exists {
			return session, nil
		}
	}
	sessiondata, err := rc.s.Load(rc.r, namespace)
	if err != nil {
		return nil, err
	}
	session := &Session{
		SessionData: sessiondata,
		store:       rc.s,
		namespace:   namespace}
	if rc.cache == nil {
		rc.cache = map[string]*Session{namespace: session}
	} else {
		rc.cache[namespace] = session
	}
	return session, nil
}
开发者ID:jtolds,项目名称:webhelp,代码行数:29,代码来源:store.go

示例8: FromContext

// FromContext returns authentication information from the context or
// nil if no such information present.
func FromContext(ctx context.Context) *Info {
	info, ok := ctx.Value(infoKey).(*Info)
	if !ok {
		return nil
	}
	return info
}
开发者ID:abbot,项目名称:go-http-auth,代码行数:9,代码来源:auth.go

示例9: SpanFromContext

// SpanFromContext returns the `Span` previously associated with `ctx`, or
// `nil` if no such `Span` could be found.
//
// NOTE: context.Context != SpanContext: the former is Go's intra-process
// context propagation mechanism, and the latter houses OpenTracing's per-Span
// identity and baggage information.
func SpanFromContext(ctx context.Context) Span {
	val := ctx.Value(activeSpanKey)
	if sp, ok := val.(Span); ok {
		return sp
	}
	return nil
}
开发者ID:opentracing,项目名称:opentracing-go,代码行数:13,代码来源:gocontext.go

示例10: Parse

func Parse(ctx context.Context) (*CommandArgument, error) {
	var (
		err        error
		commandArg *CommandArgument
		catVar     = ctx.Value("cat").(cat.Cat)
		imagePath  = ctx.Value("imagepath").(string)
	)

	params, ok := generalArgPattern.FindStringSubmatchMap(imagePath)
	if ok {
		commandArg, err = makeGeneralArg(imagePath, params)
	} else {
		params, ok = sourceDigitalMarkArgPattern.FindStringSubmatchMap(imagePath)
		if ok {
			commandArg.digitalMarkOnSource = true
			commandArg, err = makeDigitalMarkOnSourceArg(params)
		} else {
			err = errors.New("Image.Command.ParseError")
			log.WithFields(log.Fields{"uri": imagePath}).Warn(err.Error())
			util.LogErrorEvent(catVar, "URI.ParseError", "")
		}
	}

	return commandArg, err
}
开发者ID:chenbk85,项目名称:nephele,代码行数:25,代码来源:command.go

示例11: ReadTokenManagerFromContext

//ReadTokenManagerFromContext returns tokenManager from context.
// Must have been set by ContextWithTokenManager ONLY
func ReadTokenManagerFromContext(ctx context.Context) token.Manager {
	tm := ctx.Value(contextTokenManagerKey)
	if tm != nil {
		return tm.(token.Manager)
	}
	return nil
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:9,代码来源:service.go

示例12: CurrentSpan

// CurrentSpan returns the Span value for the provided Context
func CurrentSpan(ctx context.Context) *Span {
	if span := ctx.Value(contextKeyTracing); span != nil {
		return span.(*Span)
	}

	return nil
}
开发者ID:jammyluo,项目名称:tchannel,代码行数:8,代码来源:tracing.go

示例13: groupFromContext

// groupFromContext returns the Group from the ctx.
func groupFromContext(ctx context.Context) (*Group, error) {
	group, ok := ctx.Value(groupKey).(*Group)
	if !ok {
		return nil, errNoGroupFromContext
	}
	return group, nil
}
开发者ID:carriercomm,项目名称:coreos-baremetal,代码行数:8,代码来源:context.go

示例14: specFromContext

// specFromContext returns the Spec from the ctx.
func specFromContext(ctx context.Context) (*Spec, error) {
	spec, ok := ctx.Value(specKey).(*Spec)
	if !ok {
		return nil, errNoSpecFromContext
	}
	return spec, nil
}
开发者ID:carriercomm,项目名称:coreos-baremetal,代码行数:8,代码来源:context.go

示例15: contextPairs

// contextPairs takes a slice of string keys, obtains their values from the
// context.Context and returns the suitable list of key value pairs as a
// []interface{}.
func contextPairs(ctx context.Context, keys ...string) []interface{} {
	var pairs []interface{}
	for _, k := range keys {
		pairs = append(pairs, k, ctx.Value(k))
	}
	return pairs
}
开发者ID:frewsxcv,项目名称:empire,代码行数:10,代码来源:logger.go


注:本文中的golang.org/x/net/context.Context.Value方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。