mirror of
https://github.com/gin-gonic/gin.git
synced 2026-06-11 07:58:14 +08:00
Compare commits
11 Commits
02c4a3bbb8
...
be0a30ddf0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be0a30ddf0 | ||
|
|
b2b489dbf4 | ||
|
|
3ab698dc51 | ||
|
|
9914178584 | ||
|
|
915e4c90d2 | ||
|
|
26c3a62865 | ||
|
|
22c274c84b | ||
|
|
15ef1d4739 | ||
|
|
c57a166902 | ||
|
|
e7943c03dc | ||
|
|
93f51e4c68 |
2
.github/workflows/gin.yml
vendored
2
.github/workflows/gin.yml
vendored
@ -65,7 +65,7 @@ jobs:
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
- uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
${{ matrix.go-build }}
|
||||
|
||||
30
context.go
30
context.go
@ -978,18 +978,32 @@ func (c *Context) ClientIP() string {
|
||||
}
|
||||
}
|
||||
|
||||
// It also checks if the remoteIP is a trusted proxy or not.
|
||||
// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
|
||||
// defined by Engine.SetTrustedProxies()
|
||||
remoteIP := net.ParseIP(c.RemoteIP())
|
||||
if remoteIP == nil {
|
||||
return ""
|
||||
var (
|
||||
trusted bool
|
||||
remoteIP net.IP
|
||||
)
|
||||
// If gin is listening a unix socket, always trust it.
|
||||
localAddr, ok := c.Request.Context().Value(http.LocalAddrContextKey).(net.Addr)
|
||||
if ok && strings.HasPrefix(localAddr.Network(), "unix") {
|
||||
trusted = true
|
||||
}
|
||||
|
||||
// Fallback
|
||||
if !trusted {
|
||||
// It also checks if the remoteIP is a trusted proxy or not.
|
||||
// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
|
||||
// defined by Engine.SetTrustedProxies()
|
||||
remoteIP = net.ParseIP(c.RemoteIP())
|
||||
if remoteIP == nil {
|
||||
return ""
|
||||
}
|
||||
trusted = c.engine.isTrustedProxy(remoteIP)
|
||||
}
|
||||
trusted := c.engine.isTrustedProxy(remoteIP)
|
||||
|
||||
if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil {
|
||||
for _, headerName := range c.engine.RemoteIPHeaders {
|
||||
ip, valid := c.engine.validateHeader(c.requestHeader(headerName))
|
||||
headerValue := strings.Join(c.Request.Header.Values(headerName), ",")
|
||||
ip, valid := c.engine.validateHeader(headerValue)
|
||||
if valid {
|
||||
return ip
|
||||
}
|
||||
|
||||
444
context_test.go
444
context_test.go
@ -20,6 +20,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@ -75,6 +76,285 @@ func must(err error) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestContextNegotiate tests the Context.Negotiate() method
|
||||
func TestContextNegotiate(t *testing.T) {
|
||||
// Test JSON negotiation
|
||||
t.Run("negotiate JSON", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "application/json")
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON, binding.MIMEHTML},
|
||||
JSONData: data,
|
||||
HTMLName: "test.html",
|
||||
HTMLData: data,
|
||||
})
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "application/json")
|
||||
assert.Contains(t, w.Body.String(), `"message":"hello"`)
|
||||
})
|
||||
|
||||
// Test HTML negotiation
|
||||
t.Run("negotiate HTML", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, engine := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "text/html")
|
||||
|
||||
// Set up a simple HTML template
|
||||
tmpl := template.Must(template.New("test").Parse(`<h1>{{.message}}</h1>`))
|
||||
engine.SetHTMLTemplate(tmpl)
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON, binding.MIMEHTML},
|
||||
JSONData: data,
|
||||
HTMLName: "test",
|
||||
HTMLData: data,
|
||||
})
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "text/html")
|
||||
assert.Contains(t, w.Body.String(), "<h1>hello</h1>")
|
||||
})
|
||||
|
||||
// Test XML negotiation
|
||||
t.Run("negotiate XML", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "application/xml")
|
||||
|
||||
type TestData struct {
|
||||
Message string `xml:"message"`
|
||||
}
|
||||
data := TestData{Message: "hello"}
|
||||
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON, binding.MIMEXML},
|
||||
XMLData: data,
|
||||
})
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "application/xml")
|
||||
assert.Contains(t, w.Body.String(), "<message>hello</message>")
|
||||
})
|
||||
|
||||
// Test YAML negotiation
|
||||
t.Run("negotiate YAML", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "application/x-yaml")
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON, binding.MIMEYAML},
|
||||
YAMLData: data,
|
||||
})
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "application/yaml")
|
||||
assert.Contains(t, w.Body.String(), "message: hello")
|
||||
})
|
||||
|
||||
// Test TOML negotiation
|
||||
t.Run("negotiate TOML", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "application/toml")
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON, binding.MIMETOML},
|
||||
TOMLData: data,
|
||||
})
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "application/toml")
|
||||
assert.Contains(t, w.Body.String(), `message = 'hello'`)
|
||||
})
|
||||
|
||||
// Test fallback to Data field
|
||||
t.Run("fallback to Data field", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "application/json")
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON},
|
||||
Data: data, // No JSONData, should fallback to Data
|
||||
})
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "application/json")
|
||||
assert.Contains(t, w.Body.String(), `"message":"hello"`)
|
||||
})
|
||||
|
||||
// Test specific data takes precedence over Data field
|
||||
t.Run("specific data takes precedence", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "application/json")
|
||||
|
||||
jsonData := map[string]string{"type": "json"}
|
||||
fallbackData := map[string]string{"type": "fallback"}
|
||||
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON},
|
||||
JSONData: jsonData,
|
||||
Data: fallbackData,
|
||||
})
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Body.String(), `"type":"json"`)
|
||||
assert.NotContains(t, w.Body.String(), `"type":"fallback"`)
|
||||
})
|
||||
|
||||
// Test multiple Accept headers with quality values
|
||||
t.Run("multiple Accept headers with quality", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "application/xml;q=0.9, application/json;q=1.0")
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEXML, binding.MIMEJSON},
|
||||
JSONData: data,
|
||||
XMLData: data,
|
||||
})
|
||||
|
||||
// Should choose XML as it appears first in the Offered slice
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "application/xml")
|
||||
})
|
||||
|
||||
// Test wildcard Accept header
|
||||
t.Run("wildcard Accept header", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "*/*")
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON, binding.MIMEXML},
|
||||
JSONData: data,
|
||||
})
|
||||
|
||||
// Should choose the first offered format
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "application/json")
|
||||
})
|
||||
|
||||
// Test no Accept header (should default to first offered)
|
||||
t.Run("no Accept header", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
// No Accept header set
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEXML, binding.MIMEJSON},
|
||||
XMLData: data,
|
||||
JSONData: data,
|
||||
})
|
||||
|
||||
// Should choose the first offered format (XML)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "application/xml")
|
||||
})
|
||||
|
||||
// Test unsupported Accept header
|
||||
t.Run("unsupported Accept header", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "application/pdf")
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON, binding.MIMEXML},
|
||||
JSONData: data,
|
||||
})
|
||||
|
||||
// Should return 406 Not Acceptable
|
||||
assert.Equal(t, http.StatusNotAcceptable, w.Code)
|
||||
assert.True(t, c.IsAborted())
|
||||
})
|
||||
|
||||
// Test partial match in Accept header
|
||||
t.Run("partial match in Accept header", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, engine := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "text/*")
|
||||
|
||||
// Set up a simple HTML template
|
||||
tmpl := template.Must(template.New("test").Parse(`<h1>{{.message}}</h1>`))
|
||||
engine.SetHTMLTemplate(tmpl)
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON, binding.MIMEHTML},
|
||||
JSONData: data,
|
||||
HTMLName: "test",
|
||||
HTMLData: data,
|
||||
})
|
||||
|
||||
// Should match text/html
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "text/html")
|
||||
})
|
||||
|
||||
// Test YAML2 MIME type
|
||||
t.Run("negotiate YAML2 MIME type", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "application/yaml")
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEJSON, binding.MIMEYAML2},
|
||||
YAMLData: data,
|
||||
})
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "application/yaml")
|
||||
assert.Contains(t, w.Body.String(), "message: hello")
|
||||
})
|
||||
|
||||
// Test complex Accept header with multiple types and quality values
|
||||
t.Run("complex Accept header", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||
|
||||
data := map[string]string{"message": "hello"}
|
||||
c.Negotiate(http.StatusOK, Negotiate{
|
||||
Offered: []string{binding.MIMEXML, binding.MIMEJSON},
|
||||
XMLData: data,
|
||||
JSONData: data,
|
||||
})
|
||||
|
||||
// Should choose XML as it's explicitly mentioned in Accept header
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(t, w.Header().Get("Content-Type"), "application/xml")
|
||||
})
|
||||
}
|
||||
|
||||
// TestContextFile tests the Context.File() method
|
||||
func TestContextFile(t *testing.T) {
|
||||
// Test serving an existing file
|
||||
@ -179,6 +459,20 @@ func TestContextFormFileFailed(t *testing.T) {
|
||||
assert.Nil(t, f)
|
||||
}
|
||||
|
||||
func TestContextFormFileParseMultipartFormFailed(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
// Create a request with invalid multipart form data
|
||||
body := strings.NewReader("invalid multipart data")
|
||||
c.Request, _ = http.NewRequest(http.MethodPost, "/", body)
|
||||
c.Request.Header.Set("Content-Type", "multipart/form-data; boundary=invalid")
|
||||
c.engine.MaxMultipartMemory = 8 << 20
|
||||
|
||||
// This should trigger the error handling in FormFile when ParseMultipartForm fails
|
||||
f, err := c.FormFile("file")
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, f)
|
||||
}
|
||||
|
||||
func TestContextMultipartForm(t *testing.T) {
|
||||
buf := new(bytes.Buffer)
|
||||
mw := multipart.NewWriter(buf)
|
||||
@ -273,6 +567,43 @@ func TestSaveUploadedFileWithPermissionFailed(t *testing.T) {
|
||||
require.Error(t, c.SaveUploadedFile(f, "test/permission_test", mode))
|
||||
}
|
||||
|
||||
func TestSaveUploadedFileChmodFailed(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("chmod test not applicable on Windows")
|
||||
}
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
mw := multipart.NewWriter(buf)
|
||||
w, err := mw.CreateFormFile("file", "chmod_test")
|
||||
require.NoError(t, err)
|
||||
_, err = w.Write([]byte("chmod_test"))
|
||||
require.NoError(t, err)
|
||||
mw.Close()
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)
|
||||
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
f, err := c.FormFile("file")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "chmod_test", f.Filename)
|
||||
|
||||
// Create a temporary directory with restricted permissions
|
||||
tmpDir := t.TempDir()
|
||||
restrictedDir := filepath.Join(tmpDir, "restricted")
|
||||
require.NoError(t, os.MkdirAll(restrictedDir, 0o755))
|
||||
// Make the directory read-only to trigger chmod failure
|
||||
require.NoError(t, os.Chmod(restrictedDir, 0o444))
|
||||
t.Cleanup(func() {
|
||||
// Restore permissions for cleanup
|
||||
os.Chmod(restrictedDir, 0o755)
|
||||
})
|
||||
|
||||
// Try to save file with different permissions - this should fail on chmod
|
||||
var mode fs.FileMode = 0o755
|
||||
err = c.SaveUploadedFile(f, filepath.Join(restrictedDir, "subdir", "chmod_test"), mode)
|
||||
// This might fail on MkdirAll or Chmod depending on the system
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestContextReset(t *testing.T) {
|
||||
router := New()
|
||||
c := router.allocateContext(0)
|
||||
@ -896,6 +1227,20 @@ func TestContextQueryAndPostForm(t *testing.T) {
|
||||
assert.Empty(t, dicts)
|
||||
}
|
||||
|
||||
func TestContextInitFormCacheError(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
// Create a request with invalid multipart form data
|
||||
body := strings.NewReader("invalid multipart data")
|
||||
c.Request, _ = http.NewRequest(http.MethodPost, "/", body)
|
||||
c.Request.Header.Set("Content-Type", "multipart/form-data; boundary=invalid")
|
||||
c.engine.MaxMultipartMemory = 8 << 20
|
||||
|
||||
// This should trigger the error handling in initFormCache
|
||||
values, ok := c.GetPostFormArray("foo")
|
||||
assert.False(t, ok)
|
||||
assert.Empty(t, values)
|
||||
}
|
||||
|
||||
func TestContextPostFormMultipart(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = createMultipartRequest()
|
||||
@ -1143,6 +1488,37 @@ func TestContextRenderNoContentIndentedJSON(t *testing.T) {
|
||||
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
func TestContextClientIPWithMultipleHeaders(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil)
|
||||
|
||||
// Multiple X-Forwarded-For headers
|
||||
c.Request.Header.Add("X-Forwarded-For", "1.2.3.4, "+localhostIP)
|
||||
c.Request.Header.Add("X-Forwarded-For", "5.6.7.8")
|
||||
c.Request.RemoteAddr = localhostIP + ":1234"
|
||||
|
||||
c.engine.ForwardedByClientIP = true
|
||||
c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"}
|
||||
_ = c.engine.SetTrustedProxies([]string{localhostIP})
|
||||
|
||||
// Should return 5.6.7.8 (last non-trusted IP)
|
||||
assert.Equal(t, "5.6.7.8", c.ClientIP())
|
||||
}
|
||||
|
||||
func TestContextClientIPWithSingleHeader(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("X-Forwarded-For", "1.2.3.4, "+localhostIP)
|
||||
c.Request.RemoteAddr = localhostIP + ":1234"
|
||||
|
||||
c.engine.ForwardedByClientIP = true
|
||||
c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"}
|
||||
_ = c.engine.SetTrustedProxies([]string{localhostIP})
|
||||
|
||||
// Should return 1.2.3.4
|
||||
assert.Equal(t, "1.2.3.4", c.ClientIP())
|
||||
}
|
||||
|
||||
// Tests that the response is serialized as Secure JSON
|
||||
// and Content-Type is set to application/json
|
||||
func TestContextRenderSecureJSON(t *testing.T) {
|
||||
@ -1884,6 +2260,16 @@ func TestContextClientIP(t *testing.T) {
|
||||
c.engine.trustedCIDRs, _ = c.engine.prepareTrustedCIDRs()
|
||||
resetContextForClientIPTests(c)
|
||||
|
||||
// unix address
|
||||
addr := &net.UnixAddr{Net: "unix", Name: "@"}
|
||||
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), http.LocalAddrContextKey, addr))
|
||||
c.Request.RemoteAddr = addr.String()
|
||||
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||
|
||||
// reset
|
||||
c.Request = c.Request.WithContext(context.Background())
|
||||
resetContextForClientIPTests(c)
|
||||
|
||||
// Legacy tests (validating that the defaults don't break the
|
||||
// (insecure!) old behaviour)
|
||||
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||
@ -1910,7 +2296,7 @@ func TestContextClientIP(t *testing.T) {
|
||||
resetContextForClientIPTests(c)
|
||||
|
||||
// IPv6 support
|
||||
c.Request.RemoteAddr = "[::1]:12345"
|
||||
c.Request.RemoteAddr = fmt.Sprintf("[%s]:12345", localhostIPv6)
|
||||
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||
|
||||
resetContextForClientIPTests(c)
|
||||
@ -2402,6 +2788,31 @@ func TestContextBadAutoShouldBind(t *testing.T) {
|
||||
assert.False(t, c.IsAborted())
|
||||
}
|
||||
|
||||
func TestContextShouldBindBodyWithReadError(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
|
||||
// Create a request with a body that will cause read error
|
||||
c.Request, _ = http.NewRequest(http.MethodPost, "/", &errorReader{})
|
||||
|
||||
type testStruct struct {
|
||||
Foo string `json:"foo"`
|
||||
}
|
||||
obj := testStruct{}
|
||||
|
||||
// This should trigger the error handling in ShouldBindBodyWith
|
||||
err := c.ShouldBindBodyWith(&obj, binding.JSON)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "read error")
|
||||
}
|
||||
|
||||
// errorReader is a helper struct that always returns an error when Read is called
|
||||
type errorReader struct{}
|
||||
|
||||
func (e *errorReader) Read(p []byte) (n int, err error) {
|
||||
return 0, errors.New("read error")
|
||||
}
|
||||
|
||||
func TestContextShouldBindBodyWith(t *testing.T) {
|
||||
type typeA struct {
|
||||
Foo string `json:"foo" xml:"foo" binding:"required"`
|
||||
@ -2872,6 +3283,17 @@ func TestContextGetRawData(t *testing.T) {
|
||||
assert.Equal(t, "Fetch binary post data", string(data))
|
||||
}
|
||||
|
||||
func TestContextGetRawDataNilBody(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)
|
||||
c.Request.Body = nil
|
||||
|
||||
data, err := c.GetRawData()
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, data)
|
||||
assert.Contains(t, err.Error(), "cannot read nil body")
|
||||
}
|
||||
|
||||
func TestContextRenderDataFromReader(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
@ -3212,7 +3634,7 @@ func TestContextCopyShouldNotCancel(t *testing.T) {
|
||||
}()
|
||||
|
||||
addr := strings.Split(l.Addr().String(), ":")
|
||||
res, err := http.Get(fmt.Sprintf("http://127.0.0.1:%s/", addr[len(addr)-1]))
|
||||
res, err := http.Get(fmt.Sprintf("http://%s:%s/", localhostIP, addr[len(addr)-1]))
|
||||
if err != nil {
|
||||
t.Error(fmt.Errorf("request error: %w", err))
|
||||
return
|
||||
@ -3460,6 +3882,24 @@ func TestContextSetCookieData(t *testing.T) {
|
||||
setCookie := c.Writer.Header().Get("Set-Cookie")
|
||||
assert.Contains(t, setCookie, "SameSite=None")
|
||||
})
|
||||
|
||||
// Test that SameSiteDefaultMode uses context's sameSite setting
|
||||
t.Run("SameSite=Default uses context setting", func(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c.SetSameSite(http.SameSiteStrictMode)
|
||||
cookie := &http.Cookie{
|
||||
Name: "user",
|
||||
Value: "gin",
|
||||
Path: "/",
|
||||
Domain: "localhost",
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteDefaultMode,
|
||||
}
|
||||
c.SetCookieData(cookie)
|
||||
setCookie := c.Writer.Header().Get("Set-Cookie")
|
||||
assert.Contains(t, setCookie, "SameSite=Strict")
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetMapFromFormData(t *testing.T) {
|
||||
|
||||
7271
coverage.html
Normal file
7271
coverage.html
Normal file
File diff suppressed because it is too large
Load Diff
@ -124,6 +124,59 @@ func TestDebugPrintWARNINGDefaultWithUnsupportedVersion(t *testing.T) {
|
||||
assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.24+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re)
|
||||
}
|
||||
|
||||
func TestDebugPrintWARNINGDefaultLowGoVersion(t *testing.T) {
|
||||
// Test the Go version warning branch by testing getMinVer with different inputs
|
||||
// and then testing the logic directly
|
||||
|
||||
// First test getMinVer with a version that would trigger the warning
|
||||
v, err := getMinVer("go1.22.1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, uint64(22), v)
|
||||
|
||||
// Test that version 22 is less than ginSupportMinGoVer (23)
|
||||
assert.True(t, v < ginSupportMinGoVer)
|
||||
|
||||
// Test the warning message directly by capturing debugPrint output
|
||||
re := captureOutput(t, func() {
|
||||
SetMode(DebugMode)
|
||||
// Simulate the condition that would trigger the warning
|
||||
if v < ginSupportMinGoVer {
|
||||
debugPrint(`[WARNING] Now Gin requires Go 1.23+.
|
||||
|
||||
`)
|
||||
}
|
||||
debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
|
||||
|
||||
`)
|
||||
SetMode(TestMode)
|
||||
})
|
||||
|
||||
assert.Equal(t, "[GIN-debug] [WARNING] Now Gin requires Go 1.23+.\n\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n", re)
|
||||
}
|
||||
|
||||
func TestDebugPrintWithCustomFunc(t *testing.T) {
|
||||
// Test debugPrint with custom DebugPrintFunc
|
||||
originalFunc := DebugPrintFunc
|
||||
defer func() {
|
||||
DebugPrintFunc = originalFunc
|
||||
}()
|
||||
|
||||
var capturedFormat string
|
||||
var capturedValues []any
|
||||
DebugPrintFunc = func(format string, values ...any) {
|
||||
capturedFormat = format
|
||||
capturedValues = values
|
||||
}
|
||||
|
||||
SetMode(DebugMode)
|
||||
debugPrint("test %s %d", "message", 42)
|
||||
SetMode(TestMode)
|
||||
|
||||
// debugPrint automatically adds \n if not present
|
||||
assert.Equal(t, "test %s %d", capturedFormat)
|
||||
assert.Equal(t, []any{"message", 42}, capturedValues)
|
||||
}
|
||||
|
||||
func TestDebugPrintWARNINGNew(t *testing.T) {
|
||||
re := captureOutput(t, func() {
|
||||
SetMode(DebugMode)
|
||||
|
||||
@ -83,7 +83,7 @@ func TestLoadHTMLGlobDebugMode(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestH2c(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
ln, err := net.Listen("tcp", localhostIP+":0")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
37
recovery.go
37
recovery.go
@ -12,12 +12,12 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin/internal/bytesconv"
|
||||
@ -57,40 +57,33 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
|
||||
}
|
||||
return func(c *Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
if rec := recover(); rec != nil {
|
||||
// Check for a broken connection, as it is not really a
|
||||
// condition that warrants a panic stack trace.
|
||||
var brokenPipe bool
|
||||
if ne, ok := err.(*net.OpError); ok {
|
||||
var se *os.SyscallError
|
||||
if errors.As(ne, &se) {
|
||||
seStr := strings.ToLower(se.Error())
|
||||
if strings.Contains(seStr, "broken pipe") ||
|
||||
strings.Contains(seStr, "connection reset by peer") {
|
||||
brokenPipe = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if e, ok := err.(error); ok && errors.Is(e, http.ErrAbortHandler) {
|
||||
brokenPipe = true
|
||||
var isBrokenPipe bool
|
||||
err, ok := rec.(error)
|
||||
if ok {
|
||||
isBrokenPipe = errors.Is(err, syscall.EPIPE) ||
|
||||
errors.Is(err, syscall.ECONNRESET) ||
|
||||
errors.Is(err, http.ErrAbortHandler)
|
||||
}
|
||||
if logger != nil {
|
||||
if brokenPipe {
|
||||
logger.Printf("%s\n%s%s", err, secureRequestDump(c.Request), reset)
|
||||
if isBrokenPipe {
|
||||
logger.Printf("%s\n%s%s", rec, secureRequestDump(c.Request), reset)
|
||||
} else if IsDebugging() {
|
||||
logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",
|
||||
timeFormat(time.Now()), secureRequestDump(c.Request), err, stack(stackSkip), reset)
|
||||
timeFormat(time.Now()), secureRequestDump(c.Request), rec, stack(stackSkip), reset)
|
||||
} else {
|
||||
logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s",
|
||||
timeFormat(time.Now()), err, stack(stackSkip), reset)
|
||||
timeFormat(time.Now()), rec, stack(stackSkip), reset)
|
||||
}
|
||||
}
|
||||
if brokenPipe {
|
||||
if isBrokenPipe {
|
||||
// If the connection is dead, we can't write a status to it.
|
||||
c.Error(err.(error)) //nolint: errcheck
|
||||
c.Error(err) //nolint: errcheck
|
||||
c.Abort()
|
||||
} else {
|
||||
handle(c, err)
|
||||
handle(c, rec)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
@ -98,13 +98,13 @@ func TestFunction(t *testing.T) {
|
||||
func TestPanicWithBrokenPipe(t *testing.T) {
|
||||
const expectCode = 204
|
||||
|
||||
expectMsgs := map[syscall.Errno]string{
|
||||
syscall.EPIPE: "broken pipe",
|
||||
syscall.ECONNRESET: "connection reset by peer",
|
||||
expectErrnos := []syscall.Errno{
|
||||
syscall.EPIPE,
|
||||
syscall.ECONNRESET,
|
||||
}
|
||||
|
||||
for errno, expectMsg := range expectMsgs {
|
||||
t.Run(expectMsg, func(t *testing.T) {
|
||||
for _, errno := range expectErrnos {
|
||||
t.Run("Recovery from "+errno.Error(), func(t *testing.T) {
|
||||
var buf strings.Builder
|
||||
|
||||
router := New()
|
||||
@ -122,7 +122,8 @@ func TestPanicWithBrokenPipe(t *testing.T) {
|
||||
w := PerformRequest(router, http.MethodGet, "/recovery")
|
||||
// TEST
|
||||
assert.Equal(t, expectCode, w.Code)
|
||||
assert.Contains(t, strings.ToLower(buf.String()), expectMsg)
|
||||
assert.Contains(t, strings.ToLower(buf.String()), errno.Error())
|
||||
assert.NotContains(t, strings.ToLower(buf.String()), "[Recovery]")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@ -128,7 +128,9 @@ func (w *responseWriter) CloseNotify() <-chan bool {
|
||||
// Flush implements the http.Flusher interface.
|
||||
func (w *responseWriter) Flush() {
|
||||
w.WriteHeaderNow()
|
||||
w.ResponseWriter.(http.Flusher).Flush()
|
||||
if f, ok := w.ResponseWriter.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
func (w *responseWriter) Pusher() (pusher http.Pusher) {
|
||||
|
||||
6
utils.go
6
utils.go
@ -19,6 +19,12 @@ import (
|
||||
// BindKey indicates a default bind key.
|
||||
const BindKey = "_gin-gonic/gin/bindkey"
|
||||
|
||||
// localhostIP indicates the default localhost IP address.
|
||||
const localhostIP = "127.0.0.1"
|
||||
|
||||
// localhostIPv6 indicates the default localhost IPv6 address.
|
||||
const localhostIPv6 = "::1"
|
||||
|
||||
// Bind is a helper function for given interface object and returns a Gin middleware.
|
||||
func Bind(val any) HandlerFunc {
|
||||
value := reflect.ValueOf(val)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user