本文整理汇总了Golang中golang.org/x/net/context.WithValue函数的典型用法代码示例。如果您正苦于以下问题:Golang WithValue函数的具体用法?Golang WithValue怎么用?Golang WithValue使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了WithValue函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
}
开发者ID:kkaribu,项目名称:karigo,代码行数:32,代码来源:jwt_parser.go
示例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
}
开发者ID:dingotiles,项目名称:dingo-postgresql-broker,代码行数:61,代码来源:client.go
示例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)
}
开发者ID:useidel,项目名称:notary,代码行数:29,代码来源:integration_test.go
示例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"])
}
开发者ID:keichi,项目名称:scribble,代码行数:34,代码来源:note_handler_test.go
示例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)
}
}
开发者ID:stellar,项目名称:bridge-server,代码行数:26,代码来源:router_test.go
示例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)
}
}
开发者ID:alinz,项目名称:machine,代码行数:31,代码来源:local_test.go
示例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)
})
}
开发者ID:nicolai86,项目名称:dash-annotations,代码行数:31,代码来源:middleware.go
示例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)
}
}
开发者ID:applepi-icpc,项目名称:icarus,代码行数:29,代码来源:handler.go
示例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)
}
}
开发者ID:applepi-icpc,项目名称:icarus,代码行数:27,代码来源:handler.go
示例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")
}
}
开发者ID:nicolai86,项目名称:dash-annotations,代码行数:29,代码来源:users_test.go
示例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])
}
开发者ID:robmurtha,项目名称:mercury,代码行数:28,代码来源:middleware_test.go
示例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")
}
}
开发者ID:nicolai86,项目名称:dash-annotations,代码行数:31,代码来源:users_test.go
示例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()))
}
开发者ID:shamoto-donuts,项目名称:goSample,代码行数:28,代码来源:main.go
示例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")
}
开发者ID:stellar,项目名称:bridge-server,代码行数:34,代码来源:chain_test.go
示例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
}
开发者ID:jxstanford,项目名称:stormpath-sdk-go,代码行数:29,代码来源:web.go
示例16: TestContext
func TestContext(t *testing.T) {
w := New()
w.Get("/", checkContext(t, "m1", "m1"))
w.Use(func(next Handler) Handler {
return func(c *Context) error {
c.Context = context.WithValue(c.Context, "m1", "m1")
return next(c)
}
})
code, _ := doRequest(t, "GET", "/", nil, w)
isHTTPStatusOK(t, code)
w.Get("/some", checkContext(t, "m1", "m2"))
w.Use(func(next Handler) Handler {
return func(c *Context) error {
c.Context = context.WithValue(c.Context, "m1", "m2")
c.Response().WriteHeader(http.StatusBadRequest)
return next(c)
}
})
code, _ = doRequest(t, "GET", "/some", nil, w)
if code != http.StatusBadRequest {
t.Error("expecting %d, got %d", http.StatusBadRequest, code)
}
}
开发者ID:twanies,项目名称:weavebox,代码行数:25,代码来源:weavebox_test.go
示例17: AnnotateClient
// AnnotateClient returns a middleware that extracts a parent span from the
// context, produces a client (child) span from it, adds client-send and
// client-receive annotations at the boundaries, and submits the span to the
// collector. If no span is found in the context, a new span is generated and
// inserted.
func AnnotateClient(newSpan NewSpanFunc, c Collector) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
var clientSpan *Span
parentSpan, ok := FromContext(ctx)
if ok {
clientSpan = newSpan(parentSpan.TraceID(), newID(), parentSpan.SpanID())
clientSpan.runSampler = false
clientSpan.sampled = c.ShouldSample(parentSpan)
} else {
// Abnormal operation. Traces should always start server side.
// We create a root span but annotate with a warning.
traceID := newID()
clientSpan = newSpan(traceID, traceID, 0)
c.ShouldSample(clientSpan)
clientSpan.AnnotateBinary("warning", "missing server side trace")
}
ctx = context.WithValue(ctx, SpanContextKey, clientSpan) // set
defer func() { ctx = context.WithValue(ctx, SpanContextKey, parentSpan) }() // reset
clientSpan.Annotate(ClientSend)
defer func() { clientSpan.Annotate(ClientReceive); c.Collect(clientSpan) }()
return next(ctx, request)
}
}
}
开发者ID:zyanho,项目名称:kit,代码行数:30,代码来源:zipkin.go
示例18: mainRun
func mainRun() {
rootContext := context.Background()
rootContext = context.WithValue(rootContext, odbKey, odb)
rootContext = context.WithValue(rootContext, xdbKey, xdb)
rootContext = context.WithValue(rootContext, rdbKey, rdb)
rootContext = context.WithValue(rootContext, cdbKey, cdb)
for {
c, err := client.New(etcdClientConfig)
if err != nil {
panic(err)
}
kapi := client.NewKeysAPI(c)
log.WithFields(log.Fields{
"event_type": "run",
"start_time": nowPacific(),
}).Debugln("client.RunJobs running")
if err := runJobs(rootContext, kapi); err != nil {
log.WithFields(log.Fields{
"event_type": "error",
"error": err,
}).Errorln("client.RunJobs error")
}
time.Sleep(5 * time.Second)
}
}
开发者ID:agupt,项目名称:learn,代码行数:29,代码来源:main.go
示例19: TestAppendHanlerC
func TestAppendHanlerC(t *testing.T) {
init := 0
h1 := func(next HandlerC) HandlerC {
init++
return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
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) {
ctx = context.WithValue(ctx, "test", 2)
next.ServeHTTPC(ctx, w, r)
})
}
c := Chain{}
c.UseC(h1)
c.UseC(h2)
assert.Len(t, c, 2)
h := c.Handler(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// Test ordering
assert.Equal(t, 2, ctx.Value("test"), "second handler should overwrite first handler's context value")
}))
h.ServeHTTP(nil, nil)
h.ServeHTTP(nil, nil)
assert.Equal(t, 1, init, "handler init called once")
}
开发者ID:blang,项目名称:xhandler,代码行数:29,代码来源:chain_test.go
示例20: TestRotateKeyEndpoint
// RotateKey supports only timestamp and snapshot key rotation
func TestRotateKeyEndpoint(t *testing.T) {
ctx := context.WithValue(
context.Background(), notary.CtxKeyMetaStore, storage.NewMemStorage())
ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, data.ED25519Key)
ccc := utils.NewCacheControlConfig(10, false)
handler := RootHandler(ctx, nil, signed.NewEd25519(), ccc, ccc, nil)
ts := httptest.NewServer(handler)
defer ts.Close()
rolesToStatus := map[string]int{
data.CanonicalTimestampRole: http.StatusOK,
data.CanonicalSnapshotRole: http.StatusOK,
data.CanonicalTargetsRole: http.StatusNotFound,
data.CanonicalRootRole: http.StatusNotFound,
"targets/delegation": http.StatusNotFound,
"somerandomrole": http.StatusNotFound,
}
var buf bytes.Buffer
for role, expectedStatus := range rolesToStatus {
res, err := http.Post(
fmt.Sprintf("%s/v2/gun/_trust/tuf/%s.key", ts.URL, role),
"text/plain", &buf)
require.NoError(t, err)
require.Equal(t, expectedStatus, res.StatusCode)
}
}
开发者ID:jfrazelle,项目名称:notary,代码行数:28,代码来源:server_test.go
注:本文中的golang.org/x/net/context.WithValue函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论