本文整理汇总了Golang中golang.org/x/net/context.WithValue函数的典型用法代码示例。如果您正苦于以下问题:Golang WithValue函数的具体用法?Golang WithValue怎么用?Golang WithValue使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了WithValue函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: JWTParser
// JWTParser parses a JWT if one is found a request's header and stores it in
// a context.
func JWTParser(ctx context.Context, w ResponseWriter, next CtxHandlerFunc) context.Context {
r := GetRequest(ctx)
token, err := jwt.ParseFromRequest(r.R, func(token *jwt.Token) (interface{}, error) {
return publicKey, nil
})
if err == nil {
ctx = context.WithValue(ctx, ctxKey, token)
}
// Claims
idInter := Claim(ctx, "id")
id := ""
if i, ok := idInter.(string); ok {
id = i
}
ctx = context.WithValue(ctx, key("id"), id)
groupsInter := Claim(ctx, "groups")
groups := []string{}
if iS, ok := groupsInter.([]interface{}); ok {
for _, gI := range iS {
if g, ok := gI.(string); ok {
groups = append(groups, g)
}
}
}
ctx = context.WithValue(ctx, key("groups"), groups)
return next(ctx, w)
}
示例2: NewClient
// NewClient returns a new client
func NewClient(config *Config) (client *Client, err error) {
// bootstrap the config
defConfig := DefaultConfig()
if len(config.ApiAddress) == 0 {
config.ApiAddress = defConfig.ApiAddress
}
if len(config.Username) == 0 {
config.Username = defConfig.Username
}
if len(config.Password) == 0 {
config.Password = defConfig.Password
}
if len(config.Token) == 0 {
config.Token = defConfig.Token
}
ctx := oauth2.NoContext
if config.SkipSslValidation == false {
ctx = context.WithValue(ctx, oauth2.HTTPClient, defConfig.HttpClient)
} else {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
ctx = context.WithValue(ctx, oauth2.HTTPClient, &http.Client{Transport: tr})
}
endpoint, err := getInfo(config.ApiAddress, oauth2.NewClient(ctx, nil))
if err != nil {
return nil, fmt.Errorf("Could not get api /v2/info: %v", err)
}
authConfig := &oauth2.Config{
ClientID: "cf",
Scopes: []string{""},
Endpoint: oauth2.Endpoint{
AuthURL: endpoint.AuthEndpoint + "/oauth/auth",
TokenURL: endpoint.TokenEndpoint + "/oauth/token",
},
}
token, err := authConfig.PasswordCredentialsToken(ctx, config.Username, config.Password)
if err != nil {
return nil, fmt.Errorf("Error getting token: %v", err)
}
config.TokenSource = authConfig.TokenSource(ctx, token)
config.HttpClient = oauth2.NewClient(ctx, config.TokenSource)
client = &Client{
config: *config,
Endpoint: *endpoint,
}
return client, nil
}
示例3: TestValidationErrorFormat
// Ensures that the httpstore can interpret the errors returned from the server
func TestValidationErrorFormat(t *testing.T) {
ctx := context.WithValue(
context.Background(), "metaStore", storage.NewMemStorage())
ctx = context.WithValue(ctx, "keyAlgorithm", data.ED25519Key)
handler := RootHandler(nil, ctx, signed.NewEd25519())
server := httptest.NewServer(handler)
defer server.Close()
client, err := store.NewHTTPStore(
fmt.Sprintf("%s/v2/gun/_trust/tuf/", server.URL),
"",
"json",
"",
"key",
http.DefaultTransport,
)
_, repo, _ := testutils.EmptyRepo()
r, tg, sn, ts, err := testutils.Sign(repo)
assert.NoError(t, err)
rs, _, _, _, err := testutils.Serialize(r, tg, sn, ts)
assert.NoError(t, err)
err = client.SetMultiMeta(map[string][]byte{data.CanonicalRootRole: rs})
assert.Error(t, err)
assert.IsType(t, validation.ErrBadRoot{}, err)
}
示例4: TestGetNote
func TestGetNote(t *testing.T) {
assert := assert.New(t)
dbMap := initDb()
defer dbMap.Db.Close()
ctx := context.Background()
ctx = context.WithValue(ctx, "db", dbMap)
ctx = context.WithValue(ctx, "auth", &auth.AuthContext{})
dbMap.Insert(&model.Note{
Id: 0,
Title: "Test Title 1",
Content: "lorem ipsum dolor sit amet consetetur.",
OwnerId: 0,
CreatedAt: 1442284669000,
UpdatedAt: 1442292926000,
})
kami.Reset()
kami.Context = ctx
kami.Post("/api/notes/:noteId", GetNote)
server := httptest.NewServer(kami.Handler())
defer server.Close()
resp := request(t, server.URL+"/api/notes/1", http.StatusOK, nil)
assert.NotNil(resp)
note := resp.(map[string]interface{})
assert.Equal("Test Title 1", note["title"])
assert.Equal("lorem ipsum dolor sit amet consetetur.", note["content"])
assert.EqualValues(0, note["ownerId"])
assert.EqualValues(1442284669000, note["createdAt"])
assert.EqualValues(1442292926000, note["updatedAt"])
}
示例5: TestNoMatch
func TestNoMatch(t *testing.T) {
t.Parallel()
var rt router
rt.add(boolPattern(false), HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
t.Fatal("did not expect handler to be called")
}))
_, r := wr()
ctx := context.Background()
ctx = context.WithValue(ctx, internal.Pattern, boolPattern(true))
ctx = context.WithValue(ctx, internal.Pattern, boolPattern(true))
ctx = context.WithValue(ctx, "answer", 42)
ctx = context.WithValue(ctx, internal.Path, "/")
ctx = rt.route(ctx, r)
if p := ctx.Value(internal.Pattern); p != nil {
t.Errorf("unexpected pattern %v", p)
}
if h := ctx.Value(internal.Handler); h != nil {
t.Errorf("unexpected handler %v", h)
}
if h := ctx.Value("answer"); h != 42 {
t.Errorf("context didn't work: got %v, wanted %v", h, 42)
}
}
示例6: TestPassingContext
func TestPassingContext(t *testing.T) {
var state1, state2, state3 machine.State
var result int
state1 = func(runtime machine.Runtime) {
first := 1
ctx := context.WithValue(runtime.Context(), "first", first)
runtime.NextState(ctx, state2)
}
state2 = func(runtime machine.Runtime) {
first := runtime.Context().Value("first").(int)
ctx := context.WithValue(runtime.Context(), "second", first+1)
runtime.NextState(ctx, state3)
}
state3 = func(runtime machine.Runtime) {
second := runtime.Context().Value("second").(int)
result = second + 1
runtime.NextState(runtime.Context(), nil)
}
runtime := local.Runtime(context.Background(), state1)
<-runtime.Context().Done()
if result != 3 {
t.Errorf("expected %d, but got %d", 3, result)
}
}
示例7: Authenticated
// Authenticated is a middleware that checks for authentication in the request
// Authentication is identified using the laravel_session cookie.
// If no authentication is present the request is halted.
func Authenticated(h ContextHandler) ContextHandler {
return ContextHandlerFunc(func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
var db = ctx.Value(DBKey).(*sql.DB)
var encryptedSessionID = ""
for _, cookie := range req.Cookies() {
if cookie.Name == "laravel_session" {
encryptedSessionID = cookie.Value
}
}
if encryptedSessionID == "" {
return errors.New("Missing session cookie")
}
if sessionID, err := decrypt([]byte(encryptedSessionID)); err != nil {
return err
} else {
if user, err := findUserByRememberToken(db, string(sessionID)); err != nil {
return ErrAuthenticationRequired
} else {
ctx = context.WithValue(ctx, UserKey, &user)
ctx = context.WithValue(ctx, UserStoreKey, &sqlUserStorage{db: db})
}
}
return h.ServeHTTPContext(ctx, rw, req)
})
}
示例8: ParseHandle
// After `ParseJSON`
func ParseHandle(allowEmpty bool) kami.Middleware {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
var h string
_, exist := GetJSONKey(ctx, "handle")
if !exist {
if allowEmpty {
newCtx := context.WithValue(ctx, keyHandleName, "")
return context.WithValue(newCtx, keyHandle, nil)
} else {
WriteJSON(w, http.StatusBadRequest, BadField("handle"))
return nil
}
}
err := GetJSONKeyAs(ctx, "handle", &h)
if err != nil {
WriteJSON(w, http.StatusBadRequest, BadField("handle"))
return nil
}
cli, err := client.GetHandle(h)
if err != nil {
WriteJSON(w, http.StatusBadRequest, UnknownHandle)
return nil
}
newCtx := context.WithValue(ctx, keyHandleName, h)
return context.WithValue(newCtx, keyHandle, cli)
}
}
示例9: ParseAllTaskData
func ParseAllTaskData(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
session, err := store.Get(r, SessionName)
if err != nil {
log.Errorf("Frontend: Failed to save session: %s", err.Error())
WriteJSON(w, http.StatusInternalServerError, InternalError)
return nil
}
userid, ok := session.Values["user"]
if !ok {
WriteJSON(w, http.StatusUnauthorized, Unauthorized)
return nil
}
handle, _ := session.Values["handle"]
raw := manager.ListTasksData()
if userid == *flagEdgeUser {
return context.WithValue(ctx, keyAllTaskData, raw)
} else {
res := make([]icarus.TaskData, 0)
for _, v := range raw {
if v.User.UserID == userid && v.Handle == handle {
res = append(res, v)
}
}
return context.WithValue(ctx, keyAllTaskData, res)
}
}
示例10: TestUserChangeEmail_HappyPath
func TestUserChangeEmail_HappyPath(t *testing.T) {
var currentUser = dash.User{Username: "tester"}
var ctx = context.WithValue(rootCtx, UserKey, ¤tUser)
var mock = mockUserLoginStore{
updateUserWithEmail: func(username, email string) error {
if username != currentUser.Username {
t.Errorf("Expected to update user %q but was %q", currentUser.Username, username)
}
if email != "[email protected]" {
t.Errorf("Expected to update password to %q but was %q", "[email protected]", email)
}
return nil
},
}
ctx = context.WithValue(ctx, UserStoreKey, &mock)
req, _ := http.NewRequest("POST", "/users/change_email", strings.NewReader(`{"email":"[email protected]"}`))
rw := httptest.NewRecorder()
if err := UserChangeEmail(ctx, rw, req); err != nil {
t.Fatalf("UserChangeEmail errored with: %#v", err)
}
var data map[string]string
json.NewDecoder(rw.Body).Decode(&data)
if data["status"] != "success" {
t.Errorf("Expected status of %q to be %q", data["status"], "success")
}
}
示例11: TestE2E
// TestE2E verifies parent request IDs are properly set on child requests
func (suite *parentRequestIdMiddlewareSuite) TestE2E() {
cli := client.
NewClient().
SetTransport(suite.trans).
SetMiddleware([]client.ClientMiddleware{Middleware()})
dummyOrigin := mercury.NewRequest()
dummyOrigin.SetId("foobarbaz")
ctx := context.WithValue(dummyOrigin.Context(), "Current-Service", testOriginServiceName)
ctx = context.WithValue(ctx, "Current-Endpoint", "e2etest")
dummyOrigin.SetContext(ctx)
cli.Add(client.Call{
Uid: "call",
Service: testServiceName,
Endpoint: "foo",
Context: dummyOrigin,
Response: &testproto.DummyResponse{},
Body: &testproto.DummyRequest{}})
cli.Execute()
suite.Assert().NoError(cli.Errors().Combined())
rsp := cli.Response("call")
response := rsp.Body().(*testproto.DummyResponse)
suite.Assert().NotEmpty(response.Pong)
suite.Assert().Equal(response.Pong, rsp.Headers()[parentIdHeader])
}
示例12: TestUserLogout_HappyPath
func TestUserLogout_HappyPath(t *testing.T) {
var currentUser = dash.User{Username: "tester"}
var ctx = context.WithValue(rootCtx, UserKey, ¤tUser)
var mock = mockUserLoginStore{
updateUserWithToken: func(username, token string) error {
if username != currentUser.Username {
t.Errorf("Expected to update user %q but was %q", currentUser.Username, username)
}
return nil
},
}
ctx = context.WithValue(ctx, UserStoreKey, &mock)
req, _ := http.NewRequest("POST", "/users/logout", strings.NewReader(``))
rw := httptest.NewRecorder()
if err := UserLogout(ctx, rw, req); err != nil {
t.Fatalf("UserLogout errored with: %#v", err)
}
if !strings.Contains(rw.Header().Get("Set-Cookie"), "laravel_session=; Max-Age=0") {
t.Errorf("Expected Set-Cookie header to contain %v", "laravel_session")
}
var data map[string]string
json.NewDecoder(rw.Body).Decode(&data)
if data["status"] != "success" {
t.Errorf("Expected status of %q to be %q", data["status"], "success")
}
}
示例13: main
func main() {
// context
ctx = context.Background()
db := initDb()
ctx = context.WithValue(ctx, "test", "aaabbbccc")
ctx = context.WithValue(ctx, "DB", db)
// redis
redis_pool := newPool()
ctx = context.WithValue(ctx, "redis", redis_pool)
str := ctx.Value("test")
log.Println(str)
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
router, err := rest.MakeRouter(
rest.Post("/test", baseHandlerFunc(controller.Test)),
)
// 存在しないルート時
if err != nil {
log.Fatal(err)
}
api.SetApp(router)
log.Fatal(http.ListenAndServe(":9999", api.MakeHandler()))
}
示例14: TestChainHandlerC
func TestChainHandlerC(t *testing.T) {
handlerCalls := 0
h1 := func(next HandlerC) HandlerC {
return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
handlerCalls++
ctx = context.WithValue(ctx, "test", 1)
next.ServeHTTPC(ctx, w, r)
})
}
h2 := func(next HandlerC) HandlerC {
return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
handlerCalls++
ctx = context.WithValue(ctx, "test", 2)
next.ServeHTTPC(ctx, w, r)
})
}
c := Chain{}
c.UseC(h1)
c.UseC(h2)
h := c.HandlerC(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
handlerCalls++
assert.Equal(t, 2, ctx.Value("test"),
"second handler should overwrite first handler's context value")
assert.Equal(t, 1, ctx.Value("mainCtx"),
"the mainCtx value should be pass through")
}))
mainCtx := context.WithValue(context.Background(), "mainCtx", 1)
h.ServeHTTPC(mainCtx, nil, nil)
assert.Equal(t, 3, handlerCalls, "all handler called once")
}
示例15: isAuthenticated
func isAuthenticated(w http.ResponseWriter, r *http.Request, ctx context.Context) (context.Context, bool) {
if ctx.Value(AccountKey) != nil {
return ctx, true
}
application := ctx.Value(ApplicationKey).(*stormpath.Application)
//Cookie
authResult, ok := isCookieAuthenticated(r, application)
if ok {
saveAuthenticationResult(w, r, authResult, application)
return context.WithValue(ctx, AccountKey, authResult.GetAccount()), ok
}
//Token
tokenAuthResult, ok := isTokenBearerAuthenticated(r, application)
if ok {
saveAuthenticationResult(w, r, tokenAuthResult, application)
return context.WithValue(ctx, AccountKey, tokenAuthResult.GetAccount()), ok
}
//Basic
basicAuthResult, ok := isHTTPBasicAuthenticated(r, application)
if ok {
saveAuthenticationResult(w, r, basicAuthResult, application)
return context.WithValue(ctx, AccountKey, basicAuthResult.GetAccount()), ok
}
clearAuthentication(w, r, application)
return ctx, false
}