-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequestcontext.go
More file actions
39 lines (32 loc) · 958 Bytes
/
requestcontext.go
File metadata and controls
39 lines (32 loc) · 958 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Package requestcontext is a contention free http.Request adapter for golang.org/x/net/context
package requestcontext
import (
"io"
"net/http"
"golang.org/x/net/context"
)
type decoratedReadCloser struct {
body io.ReadCloser
context context.Context
}
func (w *decoratedReadCloser) Read(p []byte) (n int, err error) {
return w.body.Read(p)
}
func (w *decoratedReadCloser) Close() error {
return w.body.Close()
}
// Set this context
// call Get() prior and wrap the current context with
// one of the golang.org/x/net/context methods - see example
func Set(r *http.Request, context context.Context) {
drc := decoratedReadCloser{body: r.Body, context: context}
r.Body = &drc
}
// Get returns a parent context, will make one if needed.
// always call this before Set() to preserve context chain
func Get(r *http.Request) context.Context {
if c, ok := r.Body.(*decoratedReadCloser); ok {
return c.context
}
return context.Background()
}