mirror of
https://github.com/gin-gonic/gin.git
synced 2026-06-13 00:59:29 +08:00
Compare commits
7 Commits
c5e1ee81bd
...
02c4a3bbb8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02c4a3bbb8 | ||
|
|
d1a15347b1 | ||
|
|
64a6ed9a41 | ||
|
|
15ef1d4739 | ||
|
|
c57a166902 | ||
|
|
e7943c03dc | ||
|
|
93f51e4c68 |
@ -55,14 +55,6 @@ const ContextRequestKey ContextKeyType = 0
|
||||
// abortIndex represents a typical value used in abort functions.
|
||||
const abortIndex int8 = math.MaxInt8 >> 1
|
||||
|
||||
// safeInt8 converts int to int8 safely, capping at math.MaxInt8
|
||||
func safeInt8(n int) int8 {
|
||||
if n > math.MaxInt8 {
|
||||
return math.MaxInt8
|
||||
}
|
||||
return int8(n)
|
||||
}
|
||||
|
||||
// Context is the most important part of gin. It allows us to pass variables between middleware,
|
||||
// manage the flow, validate the JSON of a request and render a JSON response for example.
|
||||
type Context struct {
|
||||
|
||||
399
context_test.go
399
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()
|
||||
@ -2402,6 +2747,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 +3242,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)
|
||||
@ -3460,6 +3841,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)
|
||||
|
||||
54
recovery.go
54
recovery.go
@ -5,7 +5,9 @@
|
||||
package gin
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"cmp"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@ -21,9 +23,10 @@ import (
|
||||
"github.com/gin-gonic/gin/internal/bytesconv"
|
||||
)
|
||||
|
||||
const dunno = "???"
|
||||
|
||||
var dunnoBytes = []byte(dunno)
|
||||
const (
|
||||
dunno = "???"
|
||||
stackSkip = 3
|
||||
)
|
||||
|
||||
// RecoveryFunc defines the function passable to CustomRecovery.
|
||||
type RecoveryFunc func(c *Context, err any)
|
||||
@ -72,7 +75,6 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
|
||||
brokenPipe = true
|
||||
}
|
||||
if logger != nil {
|
||||
const stackSkip = 3
|
||||
if brokenPipe {
|
||||
logger.Printf("%s\n%s%s", err, secureRequestDump(c.Request), reset)
|
||||
} else if IsDebugging() {
|
||||
@ -120,8 +122,11 @@ func stack(skip int) []byte {
|
||||
buf := new(bytes.Buffer) // the returned data
|
||||
// As we loop, we open files and read them. These variables record the currently
|
||||
// loaded file.
|
||||
var lines [][]byte
|
||||
var lastFile string
|
||||
var (
|
||||
nLine string
|
||||
lastFile string
|
||||
err error
|
||||
)
|
||||
for i := skip; ; i++ { // Skip the expected number of frames
|
||||
pc, file, line, ok := runtime.Caller(i)
|
||||
if !ok {
|
||||
@ -130,25 +135,44 @@ func stack(skip int) []byte {
|
||||
// Print this much at least. If we can't find the source, it won't show.
|
||||
fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
|
||||
if file != lastFile {
|
||||
data, err := os.ReadFile(file)
|
||||
nLine, err = readNthLine(file, line-1)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
lines = bytes.Split(data, []byte{'\n'})
|
||||
lastFile = file
|
||||
}
|
||||
fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
|
||||
fmt.Fprintf(buf, "\t%s: %s\n", function(pc), cmp.Or(nLine, dunno))
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// source returns a space-trimmed slice of the n'th line.
|
||||
func source(lines [][]byte, n int) []byte {
|
||||
n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
|
||||
if n < 0 || n >= len(lines) {
|
||||
return dunnoBytes
|
||||
// readNthLine reads the nth line from the file.
|
||||
// It returns the trimmed content of the line if found,
|
||||
// or an empty string if the line doesn't exist.
|
||||
// If there's an error opening the file, it returns the error.
|
||||
func readNthLine(file string, n int) (string, error) {
|
||||
if n < 0 {
|
||||
return "", nil
|
||||
}
|
||||
return bytes.TrimSpace(lines[n])
|
||||
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
for i := 0; i < n; i++ {
|
||||
if !scanner.Scan() {
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
|
||||
if scanner.Scan() {
|
||||
return strings.TrimSpace(scanner.Text()), nil
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// function returns, if possible, the name of the function containing the PC.
|
||||
|
||||
@ -88,21 +88,6 @@ func TestPanicWithAbort(t *testing.T) {
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
}
|
||||
|
||||
func TestSource(t *testing.T) {
|
||||
bs := source(nil, 0)
|
||||
assert.Equal(t, dunnoBytes, bs)
|
||||
|
||||
in := [][]byte{
|
||||
[]byte("Hello world."),
|
||||
[]byte("Hi, gin.."),
|
||||
}
|
||||
bs = source(in, 10)
|
||||
assert.Equal(t, dunnoBytes, bs)
|
||||
|
||||
bs = source(in, 1)
|
||||
assert.Equal(t, []byte("Hello world."), bs)
|
||||
}
|
||||
|
||||
func TestFunction(t *testing.T) {
|
||||
bs := function(1)
|
||||
assert.Equal(t, dunno, bs)
|
||||
@ -331,3 +316,53 @@ func TestSecureRequestDump(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadNthLine tests the readNthLine function with various scenarios.
|
||||
func TestReadNthLine(t *testing.T) {
|
||||
// Create a temporary test file
|
||||
testContent := "line 0 \n line 1 \nline 2 \nline 3 \nline 4"
|
||||
tempFile, err := os.CreateTemp("", "testfile*.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Remove(tempFile.Name())
|
||||
|
||||
// Write test content to the temporary file
|
||||
if _, err := tempFile.WriteString(testContent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := tempFile.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Test cases
|
||||
tests := []struct {
|
||||
name string
|
||||
lineNum int
|
||||
fileName string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "Read first line", lineNum: 0, fileName: tempFile.Name(), want: "line 0", wantErr: false},
|
||||
{name: "Read middle line", lineNum: 2, fileName: tempFile.Name(), want: "line 2", wantErr: false},
|
||||
{name: "Read last line", lineNum: 4, fileName: tempFile.Name(), want: "line 4", wantErr: false},
|
||||
{name: "Line number exceeds file length", lineNum: 10, fileName: tempFile.Name(), want: "", wantErr: false},
|
||||
{name: "Negative line number", lineNum: -1, fileName: tempFile.Name(), want: "", wantErr: false},
|
||||
{name: "Non-existent file", lineNum: 1, fileName: "/non/existent/file.txt", want: "", wantErr: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := readNthLine(tt.fileName, tt.lineNum)
|
||||
assert.Equal(t, tt.wantErr, err != nil)
|
||||
assert.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkStack(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for b.Loop() {
|
||||
_ = stack(stackSkip)
|
||||
}
|
||||
}
|
||||
|
||||
9
tree.go
9
tree.go
@ -5,7 +5,6 @@
|
||||
package gin
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/url"
|
||||
"strings"
|
||||
"unicode"
|
||||
@ -78,14 +77,6 @@ func (n *node) addChild(child *node) {
|
||||
}
|
||||
}
|
||||
|
||||
// safeUint16 converts int to uint16 safely, capping at math.MaxUint16
|
||||
func safeUint16(n int) uint16 {
|
||||
if n > math.MaxUint16 {
|
||||
return math.MaxUint16
|
||||
}
|
||||
return uint16(n)
|
||||
}
|
||||
|
||||
func countParams(path string) uint16 {
|
||||
colons := strings.Count(path, ":")
|
||||
stars := strings.Count(path, "*")
|
||||
|
||||
17
utils.go
17
utils.go
@ -6,6 +6,7 @@ package gin
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
@ -162,3 +163,19 @@ func isASCII(s string) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// safeInt8 converts int to int8 safely, capping at math.MaxInt8
|
||||
func safeInt8(n int) int8 {
|
||||
if n > math.MaxInt8 {
|
||||
return math.MaxInt8
|
||||
}
|
||||
return int8(n)
|
||||
}
|
||||
|
||||
// safeUint16 converts int to uint16 safely, capping at math.MaxUint16
|
||||
func safeUint16(n int) uint16 {
|
||||
if n > math.MaxUint16 {
|
||||
return math.MaxUint16
|
||||
}
|
||||
return uint16(n)
|
||||
}
|
||||
|
||||
@ -8,6 +8,7 @@ import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
@ -148,3 +149,13 @@ func TestIsASCII(t *testing.T) {
|
||||
assert.True(t, isASCII("test"))
|
||||
assert.False(t, isASCII("🧡💛💚💙💜"))
|
||||
}
|
||||
|
||||
func TestSafeInt8(t *testing.T) {
|
||||
assert.Equal(t, int8(100), safeInt8(100))
|
||||
assert.Equal(t, int8(math.MaxInt8), safeInt8(int(math.MaxInt8)+123))
|
||||
}
|
||||
|
||||
func TestSafeUint16(t *testing.T) {
|
||||
assert.Equal(t, uint16(100), safeUint16(100))
|
||||
assert.Equal(t, uint16(math.MaxUint16), safeUint16(int(math.MaxUint16)+123))
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user