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


Golang Request.WithContext方法代码示例

本文整理汇总了Golang中net/http.Request.WithContext方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.WithContext方法的具体用法?Golang Request.WithContext怎么用?Golang Request.WithContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http.Request的用法示例。


在下文中一共展示了Request.WithContext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Set

func Set(r *http.Request, key, val interface{}) *http.Request {
	if val == nil {
		return r
	}

	return r.WithContext(context.WithValue(r.Context(), key, val))
}
开发者ID:thansau239,项目名称:gophish,代码行数:7,代码来源:context.go

示例2: getArticle

func getArticle(w http.ResponseWriter, r *http.Request) {
	// Load article.
	if chi.URLParam(r, "articleID") != "1" {
		render.Respond(w, r, data.ErrNotFound)
		return
	}
	article := &data.Article{
		ID:    1,
		Title: "Article #1",
		Data:  []string{"one", "two", "three", "four"},
		CustomDataForAuthUsers: "secret data for auth'd users only",
	}

	// Simulate some context values:
	// 1. ?auth=true simluates authenticated session/user.
	// 2. ?error=true simulates random error.
	if r.URL.Query().Get("auth") != "" {
		r = r.WithContext(context.WithValue(r.Context(), "auth", true))
	}
	if r.URL.Query().Get("error") != "" {
		render.Respond(w, r, errors.New("error"))
		return
	}

	render.Respond(w, r, article)
}
开发者ID:pressly,项目名称:chi,代码行数:26,代码来源:main.go

示例3: route

func (rt *router) route(r *http.Request) *http.Request {
	tn := &rt.wildcard
	if tn2, ok := rt.methods[r.Method]; ok {
		tn = tn2
	}

	ctx := r.Context()
	path := ctx.Value(internal.Path).(string)
	for path != "" {
		i := sort.Search(len(tn.children), func(i int) bool {
			return path[0] <= tn.children[i].prefix[0]
		})
		if i == len(tn.children) || !strings.HasPrefix(path, tn.children[i].prefix) {
			break
		}

		path = path[len(tn.children[i].prefix):]
		tn = tn.children[i].node
	}
	for _, i := range tn.routes {
		if r2 := rt.routes[i].Match(r); r2 != nil {
			return r2.WithContext(&match{
				Context: r2.Context(),
				p:       rt.routes[i].Pattern,
				h:       rt.routes[i].Handler,
			})
		}
	}
	return r.WithContext(&match{Context: ctx})
}
开发者ID:goji,项目名称:goji,代码行数:30,代码来源:router_trie.go

示例4: do

func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, error) {
	if nil == ctx || nil == ctx.Done() { // ctx.Done() is for ctx
		return c.Client.Do(req)
	}

	return c.Client.Do(req.WithContext(ctx))
}
开发者ID:tjyang,项目名称:govmomi,代码行数:7,代码来源:client.go

示例5: doRequestWithClient

func doRequestWithClient(
	ctx types.Context,
	client *http.Client,
	req *http.Request) (*http.Response, error) {
	req = req.WithContext(ctx)
	return client.Do(req)
}
开发者ID:emccode,项目名称:libstorage,代码行数:7,代码来源:utils_go17.go

示例6: setDefaultRequestContext

func (t *TreeMux) setDefaultRequestContext(r *http.Request) *http.Request {
	if t.DefaultContext != nil {
		r = r.WithContext(t.DefaultContext)
	}

	return r
}
开发者ID:itkpi,项目名称:journey,代码行数:7,代码来源:treemux_17.go

示例7: setContext

func setContext(r *http.Request, key, val interface{}) {
	if val == nil {
		return
	}

	r2 := r.WithContext(context.WithValue(r.Context(), key, val))
	*r = *r2
}
开发者ID:rsooo,项目名称:ISUCONwork,代码行数:8,代码来源:isuda.go

示例8: newRun

func newRun(w http.ResponseWriter, r *http.Request, handler []http.Handler) *Run {
	run := &Run{
		rWriter: w,
		handler: handler,
	}

	run.request = r.WithContext(context.WithValue(r.Context(), ctxRun, run))
	return run
}
开发者ID:nexcode,项目名称:wenex,代码行数:9,代码来源:un.go

示例9: ServeHTTP

// ServeHTTP implements net/http.Handler.
func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if m.root {
		ctx := r.Context()
		ctx = context.WithValue(ctx, internal.Path, r.URL.EscapedPath())
		r = r.WithContext(ctx)
	}
	r = m.router.route(r)
	m.handler.ServeHTTP(w, r)
}
开发者ID:goji,项目名称:goji,代码行数:10,代码来源:mux.go

示例10: route

func (rt *router) route(r *http.Request) *http.Request {
	for _, route := range *rt {
		if r2 := route.Match(r); r2 != nil {
			return r2.WithContext(&match{
				Context: r2.Context(),
				p:       route.Pattern,
				h:       route.Handler,
			})
		}
	}
	return r.WithContext(&match{Context: r.Context()})
}
开发者ID:goji,项目名称:goji,代码行数:12,代码来源:router_simple.go

示例11: ensureComponentsInitialize

// ensureComponentsInitialize checks if the appliance components are initialized by issuing
// `docker info` to the appliance
func (d *Dispatcher) ensureComponentsInitialize(conf *config.VirtualContainerHostConfigSpec) error {
	var (
		proto  string
		client *http.Client
		res    *http.Response
		err    error
		req    *http.Request
	)

	if conf.HostCertificate.IsNil() {
		// TLS disabled
		proto = "http"
		client = &http.Client{}
	} else {
		// TLS enabled
		proto = "https"
		// TODO: configure this when support is added for user-signed certs
		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		client = &http.Client{Transport: tr}
	}

	dockerInfoURL := fmt.Sprintf("%s://%s:%s/info", proto, d.HostIP, d.DockerPort)
	req, err = http.NewRequest("GET", dockerInfoURL, nil)
	if err != nil {
		return errors.New("invalid HTTP request for docker info")
	}
	req = req.WithContext(d.ctx)

	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	for {
		res, err = client.Do(req)
		if err == nil && res.StatusCode == http.StatusOK {
			if isPortLayerRunning(res) {
				break
			}
		}

		select {
		case <-ticker.C:
		case <-d.ctx.Done():
			return d.ctx.Err()
		}
		log.Debug("Components not initialized yet, retrying docker info request")
	}

	return nil
}
开发者ID:kjplatz,项目名称:vic,代码行数:52,代码来源:appliance.go

示例12: contextChanger

func (a *Handler) contextChanger(r *http.Request) (*http.Request, error) {
	env, err := a.EnvParser.FromRequest(r)
	if err != nil {
		return nil, err
	}

	ctx := r.Context()
	ctx = ctxerr.WithConfig(ctx, ctxerr.Config{
		StackMode:  ctxerr.StackModeMultiStack,
		StringMode: ctxerr.StringModeNone,
	})
	ctx = rellenv.WithEnv(ctx, env)
	ctx = static.NewContext(ctx, a.Static)
	return r.WithContext(ctx), nil
}
开发者ID:daaku,项目名称:rell,代码行数:15,代码来源:web.go

示例13: NewContextForRequest

func NewContextForRequest(w ResponseWriter, r *http.Request, cur_route *Route) context.Context {
	vars := cur_route.RouteVars(r)
	if vars == nil {
		vars = make(map[string]string)
	}

	req_ctx := &RequestContext{
		writer:       w,
		currentRoute: cur_route,
		routeVars:    vars,
	}

	ctx := context.WithValue(r.Context(), requestContextCtxKey, req_ctx)
	req_ctx.request = r.WithContext(ctx)
	return ctx
}
开发者ID:comstud,项目名称:go-api-controller,代码行数:16,代码来源:request.go

示例14: Do

// Do sends an HTTP request with the provided http.Client and returns
// an HTTP response.
//
// If the client is nil, http.DefaultClient is used.
//
// The provided ctx must be non-nil. If it is canceled or times out,
// ctx.Err() will be returned.
func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
	if client == nil {
		client = http.DefaultClient
	}
	resp, err := client.Do(req.WithContext(ctx))
	// If we got an error, and the context has been canceled,
	// the context's error is probably more useful.
	if err != nil {
		select {
		case <-ctx.Done():
			err = ctx.Err()
		default:
		}
	}
	return resp, err
}
开发者ID:Rudloff,项目名称:platform,代码行数:23,代码来源:ctxhttp.go

示例15: logDataAdd

// logDataAdd adds a single value to the log context
func logDataAdd(r *http.Request, key string, value interface{}) {
	var data map[string]interface{}

	ctx := r.Context()
	d := ctx.Value("log")
	switch v := d.(type) {
	case map[string]interface{}:
		data = v
	default:
		data = make(map[string]interface{})
	}

	data[key] = value

	r = r.WithContext(context.WithValue(ctx, "log", data))
}
开发者ID:sethgrid,项目名称:countmyreps,代码行数:17,代码来源:log.go


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