fix(response): send 1xx informational status codes immediately

responseWriter.WriteHeader stored every status code as the final one.
A 1xx informational code such as 103 Early Hints was therefore never
sent unless the header was flushed, and flushing it marked the response
as written: the final status the handler set afterwards was ignored
(net/http then sent 200) and Status() reported 103.

Pass 1xx codes other than 101 Switching Protocols straight to the
underlying ResponseWriter, as net/http does, without recording them as
the final status.

Fixes #3289
This commit is contained in:
adityajai119 2026-11-12 18:10:34 +05:30
parent 0f09c3a9b4
commit ac87114110
2 changed files with 43 additions and 0 deletions

View File

@ -70,6 +70,10 @@ func (w *responseWriter) WriteHeader(code int) {
debugPrint("[WARNING] Headers were already written. Wanted to override status code %d with %d", w.status, code)
return
}
if code >= http.StatusContinue && code < http.StatusOK && code != http.StatusSwitchingProtocols {
w.ResponseWriter.WriteHeader(code)
return
}
w.status = code
}
}

View File

@ -6,9 +6,13 @@ package gin
import (
"bufio"
"io"
"net"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"net/textproto"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
@ -295,6 +299,41 @@ func TestResponseWriterFlush(t *testing.T) {
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
}
func TestResponseWriterWriteHeaderInformational(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writer := &responseWriter{}
writer.reset(w)
writer.Header().Set("Link", "</style.css>; rel=preload; as=style")
writer.WriteHeader(http.StatusEarlyHints)
writer.WriteHeader(http.StatusCreated)
_, _ = writer.WriteString(strconv.Itoa(writer.Status()))
}))
defer testServer.Close()
var informational []int
var link string
trace := &httptrace.ClientTrace{
Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
informational = append(informational, code)
link = header.Get("Link")
return nil
},
}
req, err := http.NewRequestWithContext(httptrace.WithClientTrace(t.Context(), trace), http.MethodGet, testServer.URL, nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, []int{http.StatusEarlyHints}, informational)
assert.Equal(t, "</style.css>; rel=preload; as=style", link)
assert.Equal(t, http.StatusCreated, resp.StatusCode)
assert.Equal(t, "201", string(body))
}
func TestResponseWriterStatusCode(t *testing.T) {
testWriter := httptest.NewRecorder()
writer := &responseWriter{}