源文件 blog/context/gorilla/gorilla.go

     1  // +build OMIT
     2  
     3  // Package gorilla provides a go.net/context.Context implementation whose Value
     4  // method returns the values associated with a specific HTTP request in the
     5  // github.com/gorilla/context package.
     6  package gorilla
     7  
     8  import (
     9  	"net/http"
    10  
    11  	gcontext "github.com/gorilla/context"
    12  	"golang.org/x/net/context"
    13  )
    14  
    15  // NewContext returns a Context whose Value method returns values associated
    16  // with req using the Gorilla context package:
    17  // http://www.gorillatoolkit.org/pkg/context
    18  func NewContext(parent context.Context, req *http.Request) context.Context {
    19  	return &wrapper{parent, req}
    20  }
    21  
    22  type wrapper struct {
    23  	context.Context
    24  	req *http.Request
    25  }
    26  
    27  type key int
    28  
    29  const reqKey key = 0
    30  
    31  // Value returns Gorilla's context package's value for this Context's request
    32  // and key. It delegates to the parent Context if there is no such value.
    33  func (ctx *wrapper) Value(key interface{}) interface{} {
    34  	if key == reqKey {
    35  		return ctx.req
    36  	}
    37  	if val, ok := gcontext.GetOk(ctx.req, key); ok {
    38  		return val
    39  	}
    40  	return ctx.Context.Value(key)
    41  }
    42  
    43  // HTTPRequest returns the *http.Request associated with ctx using NewContext,
    44  // if any.
    45  func HTTPRequest(ctx context.Context) (*http.Request, bool) {
    46  	// We cannot use ctx.(*wrapper).req to get the request because ctx may
    47  	// be a Context derived from a *wrapper. Instead, we use Value to
    48  	// access the request if it is anywhere up the Context tree.
    49  	req, ok := ctx.Value(reqKey).(*http.Request)
    50  	return req, ok
    51  }
    52  

以纯文本方式查看