本文整理汇总了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
}
示例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)
}
示例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!"))
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}