本文整理匯總了Golang中context.WithValue函數的典型用法代碼示例。如果您正苦於以下問題:Golang WithValue函數的具體用法?Golang WithValue怎麽用?Golang WithValue使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了WithValue函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: compilePagePosts
func compilePagePosts(ctx *Context) []*helper.GoWorkerRequest {
var reqs []*helper.GoWorkerRequest
lists := ctx.Source.PagePosts
for page := range lists {
pp := lists[page]
pageKey := fmt.Sprintf("post-page-%d", pp.Pager.Current)
c := context.WithValue(context.Background(), "post-page", pp.Posts)
c = context.WithValue(c, "page", pp.Pager)
req := &helper.GoWorkerRequest{
Ctx: c,
Action: func(c context.Context) (context.Context, error) {
viewData := ctx.View()
viewData["Title"] = fmt.Sprintf("Page %d - %s", pp.Pager.Current, ctx.Source.Meta.Title)
viewData["Posts"] = pp.Posts
viewData["Pager"] = pp.Pager
viewData["PostType"] = model.TreePostList
viewData["PermaKey"] = pageKey
viewData["Hover"] = model.TreePostList
viewData["URL"] = pp.URL
return c, compile(ctx, "posts.html", viewData, pp.DestURL())
},
}
reqs = append(reqs, req)
}
return reqs
}
示例2: Pagination
// Pagination adds the values "per_page" and "page" to the context with values
// from the query params.
func Pagination(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
rawPerPage := chi.URLParam(r, "per_page")
rawPage := chi.URLParam(r, "page")
if len(rawPerPage) == 0 {
rawPerPage = "20"
}
if len(rawPage) == 0 {
rawPage = "0"
}
var err error
var perPage int
if perPage, err = strconv.Atoi(rawPerPage); err != nil {
perPage = 20
}
var page int
if page, err = strconv.Atoi(rawPage); err != nil {
page = 0
}
ctx := r.Context()
ctx = context.WithValue(ctx, 1001, perPage)
ctx = context.WithValue(ctx, 1002, page)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
示例3: compileTagPosts
func compileTagPosts(ctx *Context) []*helper.GoWorkerRequest {
var reqs []*helper.GoWorkerRequest
lists := ctx.Source.TagPosts
for t := range lists {
tp := lists[t]
c := context.WithValue(context.Background(), "post-tag", tp.Posts)
c = context.WithValue(c, "tag", tp.Tag)
req := &helper.GoWorkerRequest{
Ctx: c,
Action: func(c context.Context) (context.Context, error) {
pageURL := path.Join(ctx.Source.Meta.Path, tp.Tag.URL)
pageKey := fmt.Sprintf("post-tag-%s", t)
viewData := ctx.View()
viewData["Title"] = fmt.Sprintf("%s - %s", t, ctx.Source.Meta.Title)
viewData["Posts"] = tp.Posts
viewData["Tag"] = tp.Tag
viewData["PostType"] = model.TreePostTag
viewData["PermaKey"] = pageKey
viewData["Hover"] = model.TreePostTag
viewData["URL"] = pageURL
return c, compile(ctx, "posts.html", viewData, tp.DestURL())
},
}
reqs = append(reqs, req)
}
return reqs
}
示例4: TestNoMatch
func TestNoMatch(t *testing.T) {
t.Parallel()
var rt router
rt.add(boolPattern(false), http.HandlerFunc(func(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, pattern.Variable("answer"), 42)
ctx = context.WithValue(ctx, internal.Path, "/")
r = r.WithContext(ctx)
r = rt.route(r)
ctx = r.Context()
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(pattern.Variable("answer")); h != 42 {
t.Errorf("context didn't work: got %v, wanted %v", h, 42)
}
}
示例5: newCtxWithValues
func newCtxWithValues(c *config) context.Context {
ctx := context.Background()
ctx = context.WithValue(ctx, "googleAPIKey", c.GoogleAPIKey)
ctx = context.WithValue(ctx, "googleSearchEngineID", c.GoogleSearchEngineID)
ctx = context.WithValue(ctx, "openWeatherMapAppID", c.OpenweathermapAppID)
return ctx
}
示例6: WithClientTrace
// WithClientTrace returns a new context based on the provided parent
// ctx. HTTP client requests made with the returned context will use
// the provided trace hooks, in addition to any previous hooks
// registered with ctx. Any hooks defined in the provided trace will
// be called first.
func WithClientTrace(ctx context.Context, trace *ClientTrace) context.Context {
if trace == nil {
panic("nil trace")
}
old := ContextClientTrace(ctx)
trace.compose(old)
ctx = context.WithValue(ctx, clientEventContextKey{}, trace)
if trace.hasNetHooks() {
nt := &nettrace.Trace{
ConnectStart: trace.ConnectStart,
ConnectDone: trace.ConnectDone,
}
if trace.DNSStart != nil {
nt.DNSStart = func(name string) {
trace.DNSStart(DNSStartInfo{Host: name})
}
}
if trace.DNSDone != nil {
nt.DNSDone = func(netIPs []interface{}, coalesced bool, err error) {
addrs := make([]net.IPAddr, len(netIPs))
for i, ip := range netIPs {
addrs[i] = ip.(net.IPAddr)
}
trace.DNSDone(DNSDoneInfo{
Addrs: addrs,
Coalesced: coalesced,
Err: err,
})
}
}
ctx = context.WithValue(ctx, nettrace.TraceKey{}, nt)
}
return ctx
}
示例7: serverConnBaseContext
func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) {
ctx, cancel = context.WithCancel(context.Background())
ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr())
if hs := opts.baseConfig(); hs != nil {
ctx = context.WithValue(ctx, http.ServerContextKey, hs)
}
return
}
示例8: Handle
// Handle takes the next handler as an argument and wraps it in this middleware.
func (m *Middle) Handle(next httpware.Handler) httpware.Handler {
return httpware.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
ctx = context.WithValue(ctx, httpware.RequestContentTypeKey, GetContentMatch(r.Header.Get("Content-Type")))
ct := GetContentMatch(r.Header.Get("Accept"))
ctx = context.WithValue(ctx, httpware.ResponseContentTypeKey, ct)
w.Header().Set("Content-Type", ct.Value)
return next.ServeHTTPCtx(ctx, w, r)
})
}
示例9: handle
func handle() {
key1 := "key1"
value1 := "myValue1"
ctx := context.WithValue(context.Background(), key1, value1)
key2 := "key2"
value2 := 2
ctx = context.WithValue(ctx, key2, value2)
fmt.Println("Result1:", ctx.Value(key1).(string))
fmt.Println("Result2:", ctx.Value(key2).(int))
}
示例10: ContextWithLoggable
// ContextWithLoggable returns a derived context which contains the provided
// Loggable. Any Events logged with the derived context will include the
// provided Loggable.
func ContextWithLoggable(ctx context.Context, l Loggable) context.Context {
existing, err := MetadataFromContext(ctx)
if err != nil {
// context does not contain meta. just set the new metadata
child := context.WithValue(ctx, metadataKey, Metadata(l.Loggable()))
return child
}
merged := DeepMerge(existing, l.Loggable())
child := context.WithValue(ctx, metadataKey, merged)
return child
}
示例11: TestExistingContext
func TestExistingContext(t *testing.T) {
t.Parallel()
pat := New("/hi/:c/:a/:r/:l")
req, err := http.NewRequest("GET", "/hi/foo/bar/baz/quux", nil)
if err != nil {
panic(err)
}
ctx := context.Background()
ctx = pattern.SetPath(ctx, req.URL.EscapedPath())
ctx = context.WithValue(ctx, pattern.AllVariables, map[pattern.Variable]interface{}{
"hello": "world",
"c": "nope",
})
ctx = context.WithValue(ctx, pattern.Variable("user"), "carl")
req = req.WithContext(ctx)
req = pat.Match(req)
if req == nil {
t.Fatalf("expected pattern to match")
}
ctx = req.Context()
expected := map[pattern.Variable]interface{}{
"c": "foo",
"a": "bar",
"r": "baz",
"l": "quux",
}
for k, v := range expected {
if p := Param(req, string(k)); p != v {
t.Errorf("expected %s=%q, got %q", k, v, p)
}
}
expected["hello"] = "world"
all := ctx.Value(pattern.AllVariables).(map[pattern.Variable]interface{})
if !reflect.DeepEqual(all, expected) {
t.Errorf("expected %v, got %v", expected, all)
}
if path := pattern.Path(ctx); path != "" {
t.Errorf("expected path=%q, got %q", "", path)
}
if user := ctx.Value(pattern.Variable("user")); user != "carl" {
t.Errorf("expected user=%q, got %q", "carl", user)
}
}
示例12: TestParsePostUrlJSON
func TestParsePostUrlJSON(t *testing.T) {
body := "{\"test\":true}"
r, err := http.NewRequest("PUT", "test?test=false&id=1", strings.NewReader(body))
if err != nil {
t.Fatal("Could not build request", err)
}
r.Header.Set("Content-Type", "application/json")
r = r.WithContext(context.WithValue(r.Context(), paramsKey, ParseParams(r)))
params := GetParams(r)
val, present := params.Get("test")
if !present {
t.Fatal("Key: 'test' not found")
}
if val != true {
t.Fatal("Value of 'test' should be 'true', got: ", val)
}
val, present = params.GetFloatOk("id")
if !present {
t.Fatal("Key: 'id' not found")
}
if val != 1.0 {
t.Fatal("Value of 'id' should be 1, got: ", val)
}
}
示例13: TestRoutingVariableWithContext
func TestRoutingVariableWithContext(t *testing.T) {
var (
expected = "variable"
got string
mux = New()
w = httptest.NewRecorder()
)
appFn := func(w http.ResponseWriter, r *http.Request) {
got = GetValue(r, "vartest")
}
middlewareFn := func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "key", "customValue")
newReq := r.WithContext(ctx)
appFn(w, newReq)
}
mux.Get("/:vartest", http.HandlerFunc(middlewareFn))
r, err := http.NewRequest("GET", fmt.Sprintf("/%s", expected), nil)
if err != nil {
t.Fatal(err)
}
mux.ServeHTTP(w, r)
if got != expected {
t.Fatalf("expected %s, got %s", expected, got)
}
}
示例14: TestImbueTime
func TestImbueTime(t *testing.T) {
body := "test=true&created_at=2016-06-07T00:30Z&remind_on=2016-07-17"
r, err := http.NewRequest("PUT", "test", strings.NewReader(body))
if err != nil {
t.Fatal("Could not build request", err)
}
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r = r.WithContext(context.WithValue(r.Context(), paramsKey, ParseParams(r)))
params := GetParams(r)
type testType struct {
Test bool
CreatedAt time.Time
RemindOn *time.Time
}
var obj testType
params.Imbue(&obj)
if obj.Test != true {
t.Fatal("Value of 'test' should be 'true', got: ", obj.Test)
}
createdAt, _ := time.Parse(time.RFC3339, "2016-06-07T00:30Z00:00")
if !obj.CreatedAt.Equal(createdAt) {
t.Fatal("CreatedAt should be '2016-06-07T00:30Z', got:", obj.CreatedAt)
}
remindOn, _ := time.Parse(DateOnly, "2016-07-17")
if obj.RemindOn == nil || !obj.RemindOn.Equal(remindOn) {
t.Fatal("RemindOn should be '2016-07-17', got:", obj.RemindOn)
}
}
示例15: TestRouter
func TestRouter(t *testing.T) {
t.Parallel()
var rt router
mark := new(int)
for i, p := range TestRoutes {
i := i
p.index = i
p.mark = mark
rt.add(p, intHandler(i))
}
for i, test := range RouterTests {
r, err := http.NewRequest(test.method, test.path, nil)
if err != nil {
panic(err)
}
ctx := context.WithValue(context.Background(), internal.Path, test.path)
r = r.WithContext(ctx)
var out []int
for *mark = 0; *mark < len(TestRoutes); *mark++ {
r := rt.route(r)
ctx := r.Context()
if h := ctx.Value(internal.Handler); h != nil {
out = append(out, int(h.(intHandler)))
} else {
out = append(out, -1)
}
}
if !reflect.DeepEqual(out, test.results) {
t.Errorf("[%d] expected %v got %v", i, test.results, out)
}
}
}