Gregory Man uploaded a change:
https://go-review.googlesource.com/24660
http: Add BaseContext field to Server
The BaseContext field allow to specify context avalible in all handlers.
Fixes #16220
Change-Id: I1cbd4d84c1ae4af65fbb194b9f01bb09665a1cc8
---
M src/net/http/serve_test.go
M src/net/http/server.go
2 files changed, 35 insertions(+), 3 deletions(-)
diff --git a/src/net/http/serve_test.go b/src/net/http/serve_test.go
index 139ce3e..bb1e019 100644
--- a/src/net/http/serve_test.go
+++ b/src/net/http/serve_test.go
@@ -4227,6 +4227,31 @@
res.Body.Close()
}
+func TestServerContext_ServerBaseContext(t *testing.T) {
+ defer afterTest(t)
+ const baseCtxTestKey = 0
+ var testString = "test123"
+
+ ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r
*Request) {
+ got := r.Context().Value(baseCtxTestKey)
+ if str, ok := got.(string); !ok {
+ t.Errorf("local baseCtxTestKey value = %T; want string", got)
+ } else if str != testString {
+ t.Errorf("local baseCtxTestKey = %q; want %q", got, testString)
+ }
+ }))
+
+ ts.Config.BaseContext = context.WithValue(context.Background(),
baseCtxTestKey, testString)
+ ts.Start()
+ defer ts.Close()
+ client := &Client{}
+ res, err := client.Get(ts.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+}
+
//
https://golang.org/issue/15960
func TestHandlerSetTransferEncodingChunked(t *testing.T) {
defer afterTest(t)
diff --git a/src/net/http/server.go b/src/net/http/server.go
index 7c3237c..8f73c76 100644
--- a/src/net/http/server.go
+++ b/src/net/http/server.go
@@ -2129,6 +2129,10 @@
// standard logger.
ErrorLog *log.Logger
+ // BaseContext specifies an optional context avalible in all handlers
+ // If nil context.Background will be used
+ BaseContext context.Context
+
disableKeepAlives int32 // accessed atomically.
nextProtoOnce sync.Once // guards initialization of TLSNextProto in
Serve
nextProtoErr error
@@ -2267,9 +2271,12 @@
}
}
- // TODO: allow changing base context? can't imagine concrete
- // use cases yet.
- baseCtx := context.Background()
+ var baseCtx context.Context
+ if srv.BaseContext != nil {
+ baseCtx = srv.BaseContext
+ } else {
+ baseCtx = context.Background()
+ }
ctx := context.WithValue(baseCtx, ServerContextKey, srv)
ctx = context.WithValue(ctx, LocalAddrContextKey, l.Addr())
for {
--
https://go-review.googlesource.com/24660