reverseproxy: Support 1xx status codes (HTTP early hints) (#4882)

This commit is contained in:
Kévin Dunglas 2022-08-09 18:53:24 +02:00 committed by GitHub
parent fe61209df2
commit 085df25c7e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -23,9 +23,11 @@ import (
"io" "io"
"net" "net"
"net/http" "net/http"
"net/http/httptrace"
"net/textproto" "net/textproto"
"net/url" "net/url"
"regexp" "regexp"
"runtime"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@ -40,7 +42,11 @@ import (
"golang.org/x/net/http/httpguts" "golang.org/x/net/http/httpguts"
) )
var supports1xx bool
func init() { func init() {
supports1xx = !regexp.MustCompile(`^go1\.1(?:7|8)\.`).Match([]byte(runtime.Version()))
caddy.RegisterModule(Handler{}) caddy.RegisterModule(Handler{})
} }
@ -732,6 +738,25 @@ func (h *Handler) reverseProxy(rw http.ResponseWriter, req *http.Request, origRe
server := req.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server) server := req.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server)
shouldLogCredentials := server.Logs != nil && server.Logs.ShouldLogCredentials shouldLogCredentials := server.Logs != nil && server.Logs.ShouldLogCredentials
if supports1xx {
// Forward 1xx status codes, backported from https://github.com/golang/go/pull/53164
trace := &httptrace.ClientTrace{
Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
h := rw.Header()
copyHeader(h, http.Header(header))
rw.WriteHeader(code)
// Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses
for k := range h {
delete(h, k)
}
return nil
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
}
// do the round-trip; emit debug log with values we know are // do the round-trip; emit debug log with values we know are
// safe, or if there is no error, emit fuller log entry // safe, or if there is no error, emit fuller log entry
start := time.Now() start := time.Now()