diff --git a/src/net/http/request.go b/src/net/http/request.go index 924ca1b390b..037be35aae8 100644 --- a/src/net/http/request.go +++ b/src/net/http/request.go @@ -951,6 +951,17 @@ func (r *Request) BasicAuth() (username, password string, ok bool) { return parseBasicAuth(auth) } +// ProxyBasicAuth returns the username and password provided in the request's +// Proxy-Authorization header, if the request uses HTTP Basic Authentication. +// See RFC 2068, Section 14. +func (r *Request) ProxyBasicAuth() (username, password string, ok bool) { + auth := r.Header.Get("Proxy-Authorization") + if auth == "" { + return "", "", false + } + return parseBasicAuth(auth) +} + // parseBasicAuth parses an HTTP Basic Authentication string. // "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true). func parseBasicAuth(auth string) (username, password string, ok bool) { @@ -986,6 +997,10 @@ func (r *Request) SetBasicAuth(username, password string) { r.Header.Set("Authorization", "Basic "+basicAuth(username, password)) } +func (r *Request) SetProxyBasicAuth(username, password string) { + r.Header.Set("Proxy-Authorization", "Basic "+basicAuth(username, password)) +} + // parseRequestLine parses "GET /foo HTTP/1.1" into its three parts. func parseRequestLine(line string) (method, requestURI, proto string, ok bool) { method, rest, ok1 := strings.Cut(line, " ") diff --git a/src/net/http/request_test.go b/src/net/http/request_test.go index 2f348284de9..24868e6be6b 100644 --- a/src/net/http/request_test.go +++ b/src/net/http/request_test.go @@ -366,6 +366,14 @@ func TestSetBasicAuth(t *testing.T) { } } +func TestSetProxyBasicAuth(t *testing.T) { + r, _ := NewRequest("GET", "http://example.com/", nil) + r.SetProxyBasicAuth("Aladdin", "open sesame") + if g, e := r.Header.Get("Proxy-Authorization"), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; g != e { + t.Errorf("got header %q, want %q", g, e) + } +} + func TestMultipartRequest(t *testing.T) { // Test that we can read the values and files of a // multipart request with FormValue and FormFile, @@ -744,6 +752,18 @@ func TestParseBasicAuth(t *testing.T) { } } +func TestParseProxyBasicAuth(t *testing.T) { + for _, tt := range parseBasicAuthTests { + r, _ := NewRequest("GET", "http://example.com/", nil) + r.Header.Set("Proxy-Authorization", tt.header) + username, password, ok := r.ProxyBasicAuth() + if ok != tt.ok || username != tt.username || password != tt.password { + t.Errorf("BasicAuth() = %#v, want %#v", getBasicAuthTest{username, password, ok}, + getBasicAuthTest{tt.username, tt.password, tt.ok}) + } + } +} + type logWrites struct { t *testing.T dst *[]string