Merge branch 'master' into test/marshalxml-encodetoken-error

This commit is contained in:
c879873067877881111 2026-09-17 11:05:54 +08:00 committed by GitHub
commit 4d1eb8624f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 153 additions and 26 deletions

View File

@ -33,7 +33,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL

View File

@ -16,11 +16,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v6
uses: actions/setup-go@v7
with:
go-version: "^1"
- name: Setup golangci-lint
@ -33,7 +33,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
go: ["1.25", "1.26"]
go: ["1.26", "1.27"]
test-tags:
[
"",
@ -55,17 +55,17 @@ jobs:
GOPROXY: https://proxy.golang.org
steps:
- name: Set up Go ${{ matrix.go }}
uses: actions/setup-go@v6
uses: actions/setup-go@v7
with:
go-version: ${{ matrix.go }}
cache: false
- name: Checkout Code
uses: actions/checkout@v6
uses: actions/checkout@v7
with:
ref: ${{ github.ref }}
- uses: actions/cache@v5
- uses: actions/cache@v6
with:
path: |
${{ matrix.go-build }}
@ -78,6 +78,6 @@ jobs:
run: make test
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v6
uses: codecov/codecov-action@v7
with:
flags: ${{ matrix.os }},go-${{ matrix.go }},${{ matrix.test-tags }}

View File

@ -13,11 +13,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v6
uses: actions/setup-go@v7
with:
go-version: "^1"
- name: Run GoReleaser

View File

@ -22,7 +22,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v6
uses: actions/checkout@v7
with:
fetch-depth: 0

View File

@ -44,7 +44,7 @@ Gin combines the simplicity of Express.js-style routing with Go's performance ch
### Prerequisites
- **Go version**: Gin requires [Go](https://go.dev/) version [1.25](https://go.dev/doc/devel/release#go1.25.0) or above
- **Go version**: Gin requires [Go](https://go.dev/) version [1.26](https://go.dev/doc/devel/release#go1.26.0) or above
- **Basic Go knowledge**: Familiarity with Go syntax and package management is helpful
### Installation

View File

@ -1219,6 +1219,11 @@ func (c *Context) Render(code int, r render.Render) {
// It also updates the HTTP code and sets the Content-Type as "text/html".
// See http://golang.org/doc/articles/wiki/
func (c *Context) HTML(code int, name string, obj any) {
if c.engine.HTMLRender == nil {
c.Render(code, render.HTML{})
return
}
instance := c.engine.HTMLRender.Instance(name, obj)
c.Render(code, instance)
}

View File

@ -1345,6 +1345,82 @@ func TestContextRenderHTML(t *testing.T) {
assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
}
func TestContextRenderHTMLWithoutRenderer(t *testing.T) {
tests := []struct {
name string
method string
status int
wantErrors []string
wantAborted bool
wantNextCalled bool
}{
{
name: "body allowed",
method: http.MethodGet,
status: http.StatusAccepted,
wantErrors: []string{"html renderer is not configured"},
wantAborted: true,
},
{
name: "no content",
method: http.MethodGet,
status: http.StatusNoContent,
wantNextCalled: true,
},
{
name: "not modified",
method: http.MethodGet,
status: http.StatusNotModified,
wantNextCalled: true,
},
{
name: "head",
method: http.MethodHead,
status: http.StatusOK,
wantErrors: []string{"html renderer is not configured"},
wantAborted: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
router := New()
var contextErrors []string
var contextAborted bool
nextHandlerCalled := false
handlers := []HandlerFunc{
func(c *Context) {
c.HTML(tt.status, "index.tmpl", H{"title": "Main website"})
contextErrors = c.Errors.Errors()
contextAborted = c.IsAborted()
},
func(_ *Context) {
nextHandlerCalled = true
},
}
if tt.method == http.MethodHead {
router.HEAD("/", handlers...)
} else {
router.GET("/", handlers...)
}
req := httptest.NewRequest(tt.method, "/", nil)
require.NotPanics(t, func() {
router.ServeHTTP(w, req)
})
assert.Equal(t, tt.status, w.Code)
assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
assert.Equal(t, tt.wantErrors, contextErrors)
assert.Equal(t, tt.wantAborted, contextAborted)
assert.Equal(t, tt.wantNextCalled, nextHandlerCalled)
assert.Empty(t, w.Body.String())
})
}
}
func TestContextRenderHTML2(t *testing.T) {
w := httptest.NewRecorder()
c, router := CreateTestContext(w)

View File

@ -1156,3 +1156,22 @@ func TestUpdateRouteTreesCalledOnce(t *testing.T) {
assert.Equal(t, "ok", w.Body.String())
}
}
func TestRouterQueryMethod(t *testing.T) {
router := New()
router.QUERY("/test", func(c *Context) {
c.String(http.StatusOK, "query ok")
})
w := httptest.NewRecorder()
req, _ := http.NewRequest("QUERY", "/test", nil)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "query ok", w.Body.String())
// Other methods should not match
w2 := httptest.NewRecorder()
req2, _ := http.NewRequest(http.MethodGet, "/test", nil)
router.ServeHTTP(w2, req2)
assert.Equal(t, http.StatusNotFound, w2.Code)
}

10
go.mod
View File

@ -1,6 +1,6 @@
module github.com/gin-gonic/gin
go 1.25.0
go 1.26.0
require (
github.com/bytedance/sonic v1.15.0
@ -16,7 +16,7 @@ require (
github.com/stretchr/testify v1.11.1
github.com/ugorji/go/codec v1.3.1
go.mongodb.org/mongo-driver/v2 v2.5.0
golang.org/x/net v0.55.0
golang.org/x/net v0.57.0
google.golang.org/protobuf v1.36.11
)
@ -39,7 +39,7 @@ require (
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
go.uber.org/mock v0.6.0 // indirect
golang.org/x/arch v0.25.0 // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
golang.org/x/crypto v0.56.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
)

16
go.sum
View File

@ -79,15 +79,15 @@ go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
golang.org/x/arch v0.25.0 h1:qnk6Ksugpi5Bz32947rkUgDt9/s5qvqDPl/gBKdMJLE=
golang.org/x/arch v0.25.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@ -55,7 +55,7 @@ func cleanPath(p string) string {
// A bit more clunky without a 'lazybuf' like the path package, but the loop
// gets completely inlined (bufApp calls).
// loop has no expensive function calls (except 1x make) // So in contrast to the path package this loop has no expensive function
// So in contrast to the path package this loop has no expensive function
// calls (except make, if needed).
for r < n {

View File

@ -5,6 +5,7 @@
package render
import (
"errors"
"html/template"
"net/http"
@ -50,6 +51,8 @@ type HTML struct {
var htmlContentType = []string{"text/html; charset=utf-8"}
var errHTMLRendererNotConfigured = errors.New("html renderer is not configured")
// Instance (HTMLProduction) returns an HTML instance which it realizes Render interface.
func (r HTMLProduction) Instance(name string, data any) Render {
return HTML{
@ -88,6 +91,9 @@ func (r HTMLDebug) loadTemplate() *template.Template {
// Render (HTML) executes template and writes its result with custom ContentType for response.
func (r HTML) Render(w http.ResponseWriter) error {
r.WriteContentType(w)
if r.Template == nil {
return errHTMLRendererNotConfigured
}
if r.Name == "" {
return r.Template.Execute(w, r.Data)

View File

@ -630,6 +630,16 @@ func TestRenderHTMLTemplate(t *testing.T) {
assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
}
func TestRenderHTMLWithoutTemplate(t *testing.T) {
w := httptest.NewRecorder()
err := (HTML{}).Render(w)
require.EqualError(t, err, "html renderer is not configured")
assert.Empty(t, w.Body.String())
assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
}
func TestRenderHTMLTemplateEmptyName(t *testing.T) {
w := httptest.NewRecorder()
templ := template.Must(template.New("").Parse(`Hello {{.name}}`))

View File

@ -100,6 +100,8 @@ func (group *RouterGroup) handle(httpMethod, relativePath string, handlers Handl
// This function is intended for bulk loading and to allow the usage of less
// frequently used, non-standardized or custom methods (e.g. for internal
// communication with a proxy).
//
// It panics if httpMethod is not a valid HTTP method (uppercase ASCII letters only).
func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {
if matched := regEnLetter.MatchString(httpMethod); !matched {
panic("http method " + httpMethod + " is not valid")
@ -142,6 +144,13 @@ func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRo
return group.handle(http.MethodHead, relativePath, handlers)
}
// QUERY is a shortcut for router.Handle("QUERY", path, handlers).
// The QUERY method is defined by RFC 10008 and is used to send a query
// in the request body, similar to GET but with a body.
func (group *RouterGroup) QUERY(relativePath string, handlers ...HandlerFunc) IRoutes {
return group.handle("QUERY", relativePath, handlers)
}
// Any registers a route that matches all the HTTP methods.
// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
@ -200,6 +209,7 @@ func (group *RouterGroup) Static(relativePath, root string) IRoutes {
// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.
// Gin by default uses: gin.Dir()
// It panics if relativePath contains URL parameters (: or *).
func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes {
if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
panic("URL parameters can not be used when serving a static folder")

View File

@ -26,6 +26,7 @@ const localhostIP = "127.0.0.1"
const localhostIPv6 = "::1"
// Bind is a helper function for given interface object and returns a Gin middleware.
// It panics if val is a pointer; pass the struct value directly (e.g., gin.Bind(Struct{}) not gin.Bind(&Struct{})).
func Bind(val any) HandlerFunc {
value := reflect.ValueOf(val)
if value.Kind() == reflect.Ptr {