OSDN Git Service

new repo
[bytom/vapor.git] / net / http / httpjson / context.go
1 package httpjson
2
3 import (
4         "context"
5         "net/http"
6 )
7
8 // key is an unexported type for keys defined in this package.
9 // This prevents collisions with keys defined in other packages.
10 type key int
11
12 // Keys for HTTP objects in Contexts.
13 // They are unexported; clients use Request and ResponseWriter
14 // instead of using these keys directly.
15 const (
16         reqKey key = iota
17         respKey
18 )
19
20 // Request returns the HTTP request stored in ctx.
21 // If there is none, it panics.
22 // The context given to a handler function
23 // registered in this package is guaranteed to have
24 // a request.
25 func Request(ctx context.Context) *http.Request {
26         return ctx.Value(reqKey).(*http.Request)
27 }
28
29 // ResponseWriter returns the HTTP response writer stored in ctx.
30 // If there is none, it panics.
31 // The context given to a handler function
32 // registered in this package is guaranteed to have
33 // a response writer.
34 func ResponseWriter(ctx context.Context) http.ResponseWriter {
35         return ctx.Value(respKey).(http.ResponseWriter)
36 }
37
38 // WithRequest returns a context with an HTTP request stored in it.
39 // It is useful for testing.
40 func WithRequest(ctx context.Context, req *http.Request) context.Context {
41         return context.WithValue(ctx, reqKey, req)
42 }