本文整理汇总了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))
}
示例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)
}
示例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})
}
示例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))
}
示例5: doRequestWithClient
func doRequestWithClient(
ctx types.Context,
client *http.Client,
req *http.Request) (*http.Response, error) {
req = req.WithContext(ctx)
return client.Do(req)
}
示例6: setDefaultRequestContext
func (t *TreeMux) setDefaultRequestContext(r *http.Request) *http.Request {
if t.DefaultContext != nil {
r = r.WithContext(t.DefaultContext)
}
return r
}
示例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
}
示例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
}
示例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)
}
示例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()})
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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))
}