當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。