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


Golang context.WithValue函数代码示例

本文整理汇总了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
}
开发者ID:go-xiaohei,项目名称:pugo,代码行数:26,代码来源:compile.go

示例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)
}
开发者ID:zqzca,项目名称:back,代码行数:36,代码来源:paginate.go

示例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
}
开发者ID:go-xiaohei,项目名称:pugo,代码行数:27,代码来源:compile.go

示例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)
	}
}
开发者ID:goji,项目名称:goji,代码行数:28,代码来源:router_test.go

示例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
}
开发者ID:igungor,项目名称:ilber,代码行数:7,代码来源:main.go

示例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
}
开发者ID:achanda,项目名称:go,代码行数:40,代码来源:trace.go

示例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
}
开发者ID:jfrazelle,项目名称:s3server,代码行数:8,代码来源:go17.go

示例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)
	})
}
开发者ID:nstogner,项目名称:httpware,代码行数:11,代码来源:content.go

示例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))
}
开发者ID:t2y,项目名称:misc,代码行数:12,代码来源:main.go

示例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
}
开发者ID:ipfs,项目名称:go-log,代码行数:15,代码来源:context.go

示例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)
	}
}
开发者ID:goji,项目名称:goji,代码行数:49,代码来源:match_test.go

示例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)
	}
}
开发者ID:BakedSoftware,项目名称:go-parameters,代码行数:28,代码来源:params_test.go

示例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)
	}
}
开发者ID:nmarcetic,项目名称:mainflux,代码行数:29,代码来源:bone_context_test.go

示例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)
	}
}
开发者ID:BakedSoftware,项目名称:go-parameters,代码行数:33,代码来源:params_test.go

示例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)
		}
	}
}
开发者ID:goji,项目名称:goji,代码行数:35,代码来源:router_test.go


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