Skip to content

x/net/http2/h2c: http BaseContext/ConnContext methods are not used #37089

@jared2501

Description

@jared2501

What version of Go are you using (go version)?

go version go1.13.7 darwin/amd64

Does this issue reproduce with the latest release?

Yes

What did you do? What did you expect to see? What did you see instead?

Currently, the http2/h2c package does not use the http.Server.BaseContext or http.Server.ConnContext methods. This means if I use the h2c package to upgrade a connection, the context for the user's is inherited from the background context rather than any context returned from the BaseContext or ConnContext functions.

A possible fix would be something like this:

diff --git a/http2/h2c/h2c.go b/http2/h2c/h2c.go
index 07c5c9a..349a5e6 100644
--- a/http2/h2c/h2c.go
+++ b/http2/h2c/h2c.go
@@ -11,6 +11,7 @@ package h2c
 import (
        "bufio"
        "bytes"
+       "context"
        "encoding/base64"
        "encoding/binary"
        "errors"
@@ -84,6 +85,10 @@ func (s h2cHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
                }
                defer conn.Close()

+               ctx := context.Background()
+               if server, ok := r.Context().Value(http.ServerContextKey).(*http.Server); ok && server.ConnContext != nil {
+                       ctx = server.ConnContext(ctx, conn)
+               }
                s.s.ServeConn(conn, &http2.ServeConnOpts{Handler: s.Handler})
                return
        }
@@ -91,6 +96,10 @@ func (s h2cHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        if conn, err := h2cUpgrade(w, r); err == nil {
                defer conn.Close()

+               ctx := context.Background()
+               if server, ok := r.Context().Value(http.ServerContextKey).(*http.Server); ok && server.ConnContext != nil {
+                       ctx = server.ConnContext(ctx, conn)
+               }
                s.s.ServeConn(conn, &http2.ServeConnOpts{Handler: s.Handler})
                return
        }

Does this seem reasonable?

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions