package digestimport ()// cchal is a cached challenge and the number of times it's been used.type cchal struct { c *Challenge n int}// Transport implements http.RoundTrippertypeTransportstruct { Username string Password string// Digest computes the digest credentials. // If nil, the Digest function is used. Digest func(*http.Request, *Challenge, Options) (*Credentials, error)// FindChallenge extracts the challenge from the request headers. // If nil, the FindChallenge function is used. FindChallenge func(http.Header) (*Challenge, error)// Transport specifies the mechanism by which individual // HTTP requests are made. // If nil, DefaultTransport is used. Transport http.RoundTripper// Jar specifies the cookie jar. // // The Jar is used to insert relevant cookies into every // outbound Request and is updated with the cookie values // of every inbound Response. The Jar is consulted for every // redirect that the Client follows. // // If Jar is nil, cookies are only sent if they are explicitly // set on the Request. Jar http.CookieJar// NoReuse prevents the transport from reusing challenges. NoReuse bool// Probe discovers the challenge with a bodyless request before streaming the // body, so it's only sent once authenticated — for servers that reject the // unauthenticated request without draining the body. Applies only when uncached. Probe bool// cache of challenges indexed by host cache map[string]*cchal cacheMu sync.Mutex}// save parses the digest challenge from the response// and adds it to the cachefunc ( *Transport) ( *http.Response) error {// save cookiesif .Jar != nil { .Jar.SetCookies(.Request.URL, .Cookies()) }// find and save digest challenge := .FindChallengeif == nil { = FindChallenge } , := (.Header) .cacheMu.Lock()defer .cacheMu.Unlock()if .cache == nil { .cache = map[string]*cchal{} }// TODO: if the challenge contains a domain, we should be using that // to match against outgoing requests. We're currently ignoring // it and just matching the hostname. That being said, none of // the major browsers respect the domain either. := .Request.URL.Hostname()if != nil {// if save is being invoked, the existing cached challenge didn't workdelete(.cache, )return } .cache[] = &cchal{c: }returnnil}// digest creates credentials from the cached challengefunc ( *Transport) ( *http.Request, *Challenge, int) (*Credentials, error) { := Options{Method: .Method,URI: .URL.RequestURI(),GetBody: .GetBody,Count: ,Username: .Username,Password: .Password, }if .Digest != nil {return .Digest(, , ) }returnDigest(, )}// challenge returns a cached challenge and count for the provided requestfunc ( *Transport) ( *http.Request) (*Challenge, int, bool) { .cacheMu.Lock()defer .cacheMu.Unlock() := .URL.Hostname() , := .cache[]if ! {returnnil, 0, false }if .NoReuse {delete(.cache, ) } .n++return .c, .n, true}// prepare sets the Authorization header from a cached challenge if one exists.// It reports whether the caller should send a bodyless probe first (Probe set,// request has a body, no challenge cached yet).func ( *Transport) ( *http.Request) (bool, error) {// add cookiesif .Jar != nil {for , := range .Jar.Cookies(.URL) { .AddCookie() } }// add auth , , := .challenge()if ! {// no cached challenge yet: probe bodyless first when configured := .Body != nil && .Body != http.NoBodyreturn .Probe && , nil } , := .digest(, , )if != nil {returnfalse, }if != nil { .Header.Set("Authorization", .String()) }returnfalse, nil}// RoundTrip will try to authorize the request using a cached challenge.// If that doesn't work and we receive a 401, we'll try again using that challenge.func ( *Transport) ( *http.Request) (*http.Response, error) {// use the configured transport if there is one := .Transportif == nil { = http.DefaultTransport }// don't modify the original request , := cloner()if != nil {returnnil, }// make a copy of the request , := ()if != nil {returnnil, }// prepare the first request using a cached challenge , := .prepare()if != nil {returnnil, }// probe bodyless so the body is only streamed on the authenticated retryif { .Body = nil .ContentLength = 0 .GetBody = nil }// the first request will either succeed or return a 401 , := .RoundTrip()if != nil {return , }if .StatusCode != http.StatusUnauthorized {if ! {return , nil }// a probe response isn't valid for the caller since the body was // stripped; discard it and send the real request as-is _, _ = io.Copy(io.Discard, .Body) _ = .Body.Close() , := ()if != nil {returnnil, }return .RoundTrip() }// drain and close the first message body _, _ = io.Copy(io.Discard, .Body) _ = .Body.Close()// save the challenge for future useif := .save(); != nil {if == ErrNoChallenge {return , nil }returnnil, }// make a second copy of the request , := ()if != nil {returnnil, }// prepare the second request based on the new challengeif , := .prepare(); != nil {returnnil, }return .RoundTrip()}// CloseIdleConnections delegates the call to the underlying transport.func ( *Transport) () { := .Transportif == nil { = http.DefaultTransport }typeinterface { () }if , := .(); { .() }}// cloner returns a function which makes clones of the provided requestfunc cloner( *http.Request) (func() (*http.Request, error), error) { := .GetBody// if there's no GetBody function set we have to copy the body // into memory to use for future clonesif == nil {if .Body == nil || .Body == http.NoBody { = func() (io.ReadCloser, error) {returnhttp.NoBody, nil } } else { , := io.ReadAll(.Body)if != nil {returnnil, }if := .Body.Close(); != nil {returnnil, } = func() (io.ReadCloser, error) {returnio.NopCloser(bytes.NewReader()), nil } } }returnfunc() (*http.Request, error) { := .Clone(.Context()) , := ()if != nil {returnnil, } .Body = .GetBody = return , nil }, nil}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.