Browse Source

http2: set default User-Agent if not otherwise specified

Tests in main repo, named:

=== RUN   TestTransportUserAgent_h1
--- PASS: TestTransportUserAgent_h1 (0.00s)
=== RUN   TestTransportUserAgent_h2
--- PASS: TestTransportUserAgent_h2 (0.03s)

(in upcoming CL)

Updates golang/go#13685

Change-Id: I2b62489eb03b7ff791f1f6ae6dc9c4e4f6895d39
Reviewed-on: https://go-review.googlesource.com/18285
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Brad Fitzpatrick 10 years ago
parent
commit
1ade16a545
1 changed files with 20 additions and 0 deletions
  1. 20 0
      http2/transport.go

+ 20 - 0
http2/transport.go

@@ -39,6 +39,8 @@ const (
 	// transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
 	// a stream-level WINDOW_UPDATE for at a time.
 	transportDefaultStreamMinRefresh = 4 << 10
+
+	defaultUserAgent = "Go-http-client/2.0"
 )
 
 // Transport is an HTTP/2 Transport.
@@ -783,11 +785,26 @@ func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trail
 		cc.writeHeader("trailer", trailers)
 	}
 
+	var didUA bool
 	for k, vv := range req.Header {
 		lowKey := strings.ToLower(k)
 		if lowKey == "host" {
 			continue
 		}
+		if lowKey == "user-agent" {
+			// Match Go's http1 behavior: at most one
+			// User-Agent.  If set to nil or empty string,
+			// then omit it.  Otherwise if not mentioned,
+			// include the default (below).
+			didUA = true
+			if len(vv) < 1 {
+				continue
+			}
+			vv = vv[:1]
+			if vv[0] == "" {
+				continue
+			}
+		}
 		for _, v := range vv {
 			cc.writeHeader(lowKey, v)
 		}
@@ -795,6 +812,9 @@ func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trail
 	if addGzipHeader {
 		cc.writeHeader("accept-encoding", "gzip")
 	}
+	if !didUA {
+		cc.writeHeader("user-agent", defaultUserAgent)
+	}
 	return cc.hbuf.Bytes()
 }