cmd/go: set a http user agent

go.dev/issue/35699 was a declined proposal to add the go toolchain version
as the user agent on the grounds of privacy.
However, it'd still be useful to identify cmd/go from the sea
of other web clients written in Go with a fixed string user agent.

Updates #35699
Fixes #78891

Change-Id: I872ce567995bdf3f9e968e7aa80e227e6a6a6964
Reviewed-on: https://go-review.googlesource.com/c/go/+/769500
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Michael Matloob <matloob@golang.org>
Reviewed-by: Michael Matloob <matloob@google.com>
Auto-Submit: Sean Liao <sean@liao.dev>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
This commit is contained in:
Sean Liao 2026-04-21 19:33:14 +01:00 committed by Gopher Robot
parent d8cab4c45a
commit 0e9a844b0d
2 changed files with 41 additions and 0 deletions

View file

@ -31,6 +31,8 @@ import (
"cmd/internal/browser"
)
const userAgent = "GoCommand/1 (+https://go.dev/cmd/go)"
// impatientInsecureHTTPClient is used with GOINSECURE,
// when we're connecting to https servers that might not be there
// or might be using self-signed certificates.
@ -146,6 +148,7 @@ func get(security SecurityMode, url *urlpkg.URL) (*Response, error) {
req.Host = req.URL.Host
req.URL.Host = t.ToHost
}
req.Header.Set("User-Agent", userAgent)
release, err := base.AcquireNet()
if err != nil {

View file

@ -0,0 +1,38 @@
// Copyright 2026 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
func TestUserAgent(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(r.UserAgent()))
}))
defer ts.Close()
u, err := url.Parse(ts.URL)
if err != nil {
t.Fatal("parse httptest url:", err)
}
res, err := Get(Insecure, u)
if err != nil {
t.Error("http get:", err)
}
b, err := io.ReadAll(res.Body)
if err != nil {
t.Error("read response body:", err)
}
gotUserAgent := string(bytes.TrimSpace(b))
if gotUserAgent != userAgent {
t.Errorf("User-Agent: %s, want %s", gotUserAgent, userAgent)
}
}