mirror of
https://github.com/gin-gonic/gin.git
synced 2026-06-12 00:28:37 +08:00
Compare commits
5 Commits
d660a2aa54
...
c79b8539c2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c79b8539c2 | ||
|
|
81dba46872 | ||
|
|
0c219e7902 | ||
|
|
00900fb3e1 | ||
|
|
a7b757e338 |
4
.github/workflows/gin.yml
vendored
4
.github/workflows/gin.yml
vendored
@ -26,14 +26,14 @@ jobs:
|
||||
- name: Setup golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
version: v2.6
|
||||
version: v2.9
|
||||
args: --verbose
|
||||
test:
|
||||
needs: lint
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
go: ["1.24", "1.25"]
|
||||
go: ["1.24", "1.25", "1.26"]
|
||||
test-tags:
|
||||
[
|
||||
"",
|
||||
|
||||
32
.github/workflows/trivy-scan.yml
vendored
32
.github/workflows/trivy-scan.yml
vendored
@ -9,7 +9,7 @@ on:
|
||||
- master
|
||||
schedule:
|
||||
# Run daily at 00:00 UTC
|
||||
- cron: '0 0 * * *'
|
||||
- cron: "0 0 * * *"
|
||||
workflow_dispatch: # Allow manual trigger
|
||||
|
||||
permissions:
|
||||
@ -27,30 +27,30 @@ jobs:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Run Trivy vulnerability scanner (source code)
|
||||
uses: aquasecurity/trivy-action@0.34.0
|
||||
uses: aquasecurity/trivy-action@0.34.1
|
||||
with:
|
||||
scan-type: 'fs'
|
||||
scan-ref: '.'
|
||||
scanners: 'vuln,secret,misconfig'
|
||||
format: 'sarif'
|
||||
output: 'trivy-results.sarif'
|
||||
severity: 'CRITICAL,HIGH,MEDIUM'
|
||||
scan-type: "fs"
|
||||
scan-ref: "."
|
||||
scanners: "vuln,secret,misconfig"
|
||||
format: "sarif"
|
||||
output: "trivy-results.sarif"
|
||||
severity: "CRITICAL,HIGH,MEDIUM"
|
||||
ignore-unfixed: true
|
||||
|
||||
- name: Upload Trivy results to GitHub Security tab
|
||||
uses: github/codeql-action/upload-sarif@v4
|
||||
if: always()
|
||||
with:
|
||||
sarif_file: 'trivy-results.sarif'
|
||||
sarif_file: "trivy-results.sarif"
|
||||
|
||||
- name: Run Trivy scanner (table output for logs)
|
||||
uses: aquasecurity/trivy-action@0.34.0
|
||||
uses: aquasecurity/trivy-action@0.34.1
|
||||
if: always()
|
||||
with:
|
||||
scan-type: 'fs'
|
||||
scan-ref: '.'
|
||||
scanners: 'vuln,secret,misconfig'
|
||||
format: 'table'
|
||||
severity: 'CRITICAL,HIGH,MEDIUM'
|
||||
scan-type: "fs"
|
||||
scan-ref: "."
|
||||
scanners: "vuln,secret,misconfig"
|
||||
format: "table"
|
||||
severity: "CRITICAL,HIGH,MEDIUM"
|
||||
ignore-unfixed: true
|
||||
exit-code: '1'
|
||||
exit-code: "1"
|
||||
|
||||
100
context.go
100
context.go
@ -5,6 +5,7 @@
|
||||
package gin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@ -94,6 +95,10 @@ type Context struct {
|
||||
// SameSite allows a server to define a cookie attribute making it impossible for
|
||||
// the browser to send this cookie along with cross-site requests.
|
||||
sameSite http.SameSite
|
||||
|
||||
internalContextMu sync.RWMutex
|
||||
internalContext context.Context
|
||||
internalContextCancelCause context.CancelCauseFunc
|
||||
}
|
||||
|
||||
/************************************/
|
||||
@ -115,6 +120,10 @@ func (c *Context) reset() {
|
||||
c.sameSite = 0
|
||||
*c.params = (*c.params)[:0]
|
||||
*c.skippedNodes = (*c.skippedNodes)[:0]
|
||||
|
||||
if c.useInternalContext() {
|
||||
c.WithInternalContext(context.Background())
|
||||
}
|
||||
}
|
||||
|
||||
// Copy returns a copy of the current context that can be safely used outside the request's scope.
|
||||
@ -1429,6 +1438,49 @@ func (c *Context) SetAccepted(formats ...string) {
|
||||
/***** GOLANG.ORG/X/NET/CONTEXT *****/
|
||||
/************************************/
|
||||
|
||||
// WithInternalContext replaces the internal context stored with the provided one in a thread safe manner.
|
||||
// It's important that any context you pass in is not something the wraps *gin.Context,
|
||||
// if you want to wrap a context and then provide it to WithInternalContext, use InternalContext().
|
||||
// If you don't plan to provide the context back to WithInternalContext you can safely use *Context directly.
|
||||
// Otherwise you'll end up with a stack overflow.
|
||||
//
|
||||
// For example:
|
||||
// var c *Context // given a context
|
||||
// // you can safely wrap it and pass it downstream
|
||||
// myDownstreamFunction(context.WithValue(c, ...))
|
||||
//
|
||||
// // but when you want to call WithInternalContext you should do it like this
|
||||
// c.WithInternalContext(context.WithValue(c.InternalContext(), ...))
|
||||
func (c *Context) WithInternalContext(ctx context.Context) {
|
||||
if !c.useInternalContext() {
|
||||
panic("Can't use WithInternalContext when UseInternalContext is false")
|
||||
}
|
||||
|
||||
c.internalContextMu.Lock()
|
||||
defer c.internalContextMu.Unlock()
|
||||
|
||||
c.internalContext, c.internalContextCancelCause = context.WithCancelCause(ctx)
|
||||
}
|
||||
|
||||
// InternalContext provides the currently stored internal context in a thread safe manner.
|
||||
// Use this if you want to wrap a context.Context which you'll end up providing to WithInternalContext.
|
||||
// If you don't plan to provide the context back to WithInternalContext you can safely use *Context directly.
|
||||
func (c *Context) InternalContext() context.Context {
|
||||
if !c.useInternalContext() {
|
||||
panic("Can't use InternalContext when UseInternalContext is false")
|
||||
}
|
||||
|
||||
c.internalContextMu.RLock()
|
||||
defer c.internalContextMu.RUnlock()
|
||||
|
||||
return c.internalContext
|
||||
}
|
||||
|
||||
// hasRequestContext returns whether c.Request has Context and fallback.
|
||||
func (c *Context) useInternalContext() bool {
|
||||
return c.engine != nil && c.engine.UseInternalContext
|
||||
}
|
||||
|
||||
// hasRequestContext returns whether c.Request has Context and fallback.
|
||||
func (c *Context) hasRequestContext() bool {
|
||||
hasFallback := c.engine != nil && c.engine.ContextWithFallback
|
||||
@ -1438,26 +1490,44 @@ func (c *Context) hasRequestContext() bool {
|
||||
|
||||
// Deadline returns that there is no deadline (ok==false) when c.Request has no Context.
|
||||
func (c *Context) Deadline() (deadline time.Time, ok bool) {
|
||||
if !c.hasRequestContext() {
|
||||
return
|
||||
if c.useInternalContext() {
|
||||
c.internalContextMu.RLock()
|
||||
defer c.internalContextMu.RUnlock()
|
||||
|
||||
return c.internalContext.Deadline()
|
||||
} else if c.hasRequestContext() {
|
||||
return c.Request.Context().Deadline()
|
||||
}
|
||||
return c.Request.Context().Deadline()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Done returns nil (chan which will wait forever) when c.Request has no Context.
|
||||
func (c *Context) Done() <-chan struct{} {
|
||||
if !c.hasRequestContext() {
|
||||
return nil
|
||||
if c.useInternalContext() {
|
||||
c.internalContextMu.RLock()
|
||||
defer c.internalContextMu.RUnlock()
|
||||
|
||||
return c.internalContext.Done()
|
||||
} else if c.hasRequestContext() {
|
||||
return c.Request.Context().Done()
|
||||
}
|
||||
return c.Request.Context().Done()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Err returns nil when c.Request has no Context.
|
||||
func (c *Context) Err() error {
|
||||
if !c.hasRequestContext() {
|
||||
return nil
|
||||
if c.useInternalContext() {
|
||||
c.internalContextMu.RLock()
|
||||
defer c.internalContextMu.RUnlock()
|
||||
|
||||
return c.internalContext.Err()
|
||||
} else if c.hasRequestContext() {
|
||||
return c.Request.Context().Err()
|
||||
}
|
||||
return c.Request.Context().Err()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the value associated with this context for key, or nil
|
||||
@ -1475,8 +1545,14 @@ func (c *Context) Value(key any) any {
|
||||
return val
|
||||
}
|
||||
}
|
||||
if !c.hasRequestContext() {
|
||||
return nil
|
||||
if c.useInternalContext() {
|
||||
c.internalContextMu.RLock()
|
||||
defer c.internalContextMu.RUnlock()
|
||||
|
||||
return c.internalContext.Value(key)
|
||||
} else if c.hasRequestContext() {
|
||||
return c.Request.Context().Value(key)
|
||||
}
|
||||
return c.Request.Context().Value(key)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
136
context_test.go
136
context_test.go
@ -3239,6 +3239,142 @@ func TestContextWithFallbackValueFromRequestContext(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextUseInternalContextDeadline(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder(), func(c *Context) {
|
||||
// enable UseInternalContext feature flag
|
||||
c.engine.UseInternalContext = true
|
||||
})
|
||||
|
||||
deadline, ok := c.Deadline()
|
||||
assert.Zero(t, deadline)
|
||||
assert.False(t, ok)
|
||||
|
||||
c2, _ := CreateTestContext(httptest.NewRecorder(), func(c *Context) {
|
||||
// enable UseInternalContext feature flag
|
||||
c.engine.UseInternalContext = true
|
||||
})
|
||||
|
||||
d := time.Now().Add(time.Second)
|
||||
ctx, cancel := context.WithDeadline(context.Background(), d)
|
||||
defer cancel()
|
||||
c2.WithInternalContext(ctx)
|
||||
deadline, ok = c2.Deadline()
|
||||
assert.Equal(t, d, deadline)
|
||||
assert.True(t, ok)
|
||||
}
|
||||
|
||||
func TestContextUseInternalContextDone(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder(), func(c *Context) {
|
||||
// enable UseInternalContext feature flag
|
||||
c.engine.UseInternalContext = true
|
||||
})
|
||||
|
||||
assert.Nil(t, c.Done())
|
||||
|
||||
c2, _ := CreateTestContext(httptest.NewRecorder(), func(c *Context) {
|
||||
// enable UseInternalContext feature flag
|
||||
c.engine.UseInternalContext = true
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
c2.WithInternalContext(ctx)
|
||||
cancel()
|
||||
assert.NotNil(t, <-c2.Done())
|
||||
}
|
||||
|
||||
func TestContextUseInternalContextErr(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder(), func(c *Context) {
|
||||
// enable UseInternalContext feature flag
|
||||
c.engine.UseInternalContext = true
|
||||
})
|
||||
|
||||
require.NoError(t, c.Err())
|
||||
|
||||
c2, _ := CreateTestContext(httptest.NewRecorder(), func(c *Context) {
|
||||
// enable UseInternalContext feature flag
|
||||
c.engine.UseInternalContext = true
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
c2.WithInternalContext(ctx)
|
||||
cancel()
|
||||
|
||||
assert.EqualError(t, c2.Err(), context.Canceled.Error())
|
||||
}
|
||||
|
||||
func TestContextUseInternalContextValue(t *testing.T) {
|
||||
type contextKey string
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
getContextAndKey func() (*Context, any)
|
||||
value any
|
||||
}{
|
||||
{
|
||||
name: "c with struct context key",
|
||||
getContextAndKey: func() (*Context, any) {
|
||||
type KeyStruct struct{} // https://staticcheck.dev/docs/checks/#SA1029
|
||||
var key KeyStruct
|
||||
c, _ := CreateTestContext(httptest.NewRecorder(), func(c *Context) {
|
||||
// enable UseInternalContext feature flag
|
||||
c.engine.UseInternalContext = true
|
||||
})
|
||||
c.WithInternalContext(context.WithValue(context.TODO(), key, "value"))
|
||||
return c, key
|
||||
},
|
||||
value: "value",
|
||||
},
|
||||
{
|
||||
name: "c with struct context key and request context with different value",
|
||||
getContextAndKey: func() (*Context, any) {
|
||||
type KeyStruct struct{} // https://staticcheck.dev/docs/checks/#SA1029
|
||||
var key KeyStruct
|
||||
c, _ := CreateTestContext(httptest.NewRecorder(), func(c *Context) {
|
||||
// enable UseInternalContext feature flag
|
||||
c.engine.UseInternalContext = true
|
||||
// enable ContextWithFallback feature flag
|
||||
c.engine.ContextWithFallback = true
|
||||
c.Request, _ = http.NewRequest(http.MethodPost, "/", nil)
|
||||
})
|
||||
c.WithInternalContext(context.WithValue(context.TODO(), key, "value"))
|
||||
c.Request = c.Request.WithContext(context.WithValue(context.TODO(), key, "other value"))
|
||||
return c, key
|
||||
},
|
||||
value: "value",
|
||||
},
|
||||
{
|
||||
name: "c with string context key",
|
||||
getContextAndKey: func() (*Context, any) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder(), func(c *Context) {
|
||||
// enable UseInternalContext feature flag
|
||||
c.engine.UseInternalContext = true
|
||||
})
|
||||
c.WithInternalContext(context.WithValue(context.TODO(), contextKey("key"), "value"))
|
||||
return c, contextKey("key")
|
||||
},
|
||||
value: "value",
|
||||
},
|
||||
{
|
||||
name: "c with background internal context",
|
||||
getContextAndKey: func() (*Context, any) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder(), func(c *Context) {
|
||||
// enable UseInternalContext feature flag
|
||||
c.engine.UseInternalContext = true
|
||||
})
|
||||
c.WithInternalContext(context.Background())
|
||||
return c, "key"
|
||||
},
|
||||
value: nil,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c, key := tt.getContextAndKey()
|
||||
assert.Equal(t, tt.value, c.Value(key))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextCopyShouldNotCancel(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
25
gin.go
25
gin.go
@ -169,9 +169,14 @@ type Engine struct {
|
||||
// UseH2C enable h2c support.
|
||||
UseH2C bool
|
||||
|
||||
// ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil.
|
||||
// ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value()
|
||||
// through Context.Request when Context.Request.Context() is not nil.
|
||||
ContextWithFallback bool
|
||||
|
||||
// UseInternalContext enable fallback Context.Deadline(), Context.Done(), Context.Err()
|
||||
// through InternalContext and supersedes ContextWithFallback
|
||||
UseInternalContext bool
|
||||
|
||||
delims render.Delims
|
||||
secureJSONPrefix string
|
||||
HTMLRender render.HTMLRender
|
||||
@ -669,6 +674,24 @@ func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
c.Request = req
|
||||
c.reset()
|
||||
|
||||
// If we're using internalContext then we need to pass on errors from the request context
|
||||
if c.useInternalContext() {
|
||||
reqCtx := req.Context()
|
||||
|
||||
// we need to get the cancelCause function now, so that we have the function for this request
|
||||
// because the c is a pointer to a Context that will possibly go back into the pool and be reused
|
||||
c.internalContextMu.RLock()
|
||||
cancelCause := c.internalContextCancelCause
|
||||
c.internalContextMu.RUnlock()
|
||||
|
||||
go func() {
|
||||
<-reqCtx.Done()
|
||||
if err := reqCtx.Err(); err != nil {
|
||||
cancelCause(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
engine.handleHTTPRequest(c)
|
||||
|
||||
engine.pool.Put(c)
|
||||
|
||||
4
go.mod
4
go.mod
@ -7,7 +7,7 @@ toolchain go1.24.7
|
||||
require (
|
||||
github.com/bytedance/sonic v1.15.0
|
||||
github.com/gin-contrib/sse v1.1.0
|
||||
github.com/go-playground/validator/v10 v10.28.0
|
||||
github.com/go-playground/validator/v10 v10.30.1
|
||||
github.com/goccy/go-json v0.10.5
|
||||
github.com/goccy/go-yaml v1.19.2
|
||||
github.com/json-iterator/go v1.1.12
|
||||
@ -29,7 +29,7 @@ require (
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.10 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
|
||||
8
go.sum
8
go.sum
@ -10,8 +10,8 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
@ -20,8 +20,8 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688=
|
||||
github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=
|
||||
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
|
||||
@ -14,9 +14,12 @@ import (
|
||||
// This is useful for tests that need to set up a new Gin engine instance
|
||||
// along with a context, for example, to test middleware that doesn't depend on
|
||||
// specific routes. The ResponseWriter `w` is used to initialize the context's writer.
|
||||
func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {
|
||||
func CreateTestContext(w http.ResponseWriter, opts ...func(c *Context)) (c *Context, r *Engine) {
|
||||
r = New()
|
||||
c = r.allocateContext(0)
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
}
|
||||
c.reset()
|
||||
c.writermem.reset(w)
|
||||
return
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user