mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-23 11:33:37 +08:00
Merge branch 'master' into testify
This commit is contained in:
commit
5006019585
2
.github/workflows/gin.yml
vendored
2
.github/workflows/gin.yml
vendored
@ -33,7 +33,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
go: ["1.25", "1.26"]
|
||||
go: ["1.26", "1.27"]
|
||||
test-tags:
|
||||
[
|
||||
"",
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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)
|
||||
}
|
||||
|
||||
@ -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)
|
||||
|
||||
19
gin_test.go
19
gin_test.go
@ -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
10
go.mod
@ -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.12.1
|
||||
github.com/ugorji/go/codec v1.3.1
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0
|
||||
golang.org/x/net v0.56.0
|
||||
golang.org/x/net v0.57.0
|
||||
google.golang.org/protobuf v1.36.11
|
||||
)
|
||||
|
||||
@ -35,7 +35,7 @@ require (
|
||||
go.uber.org/mock v0.6.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/arch v0.25.0 // indirect
|
||||
golang.org/x/crypto v0.53.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/text v0.39.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
16
go.sum
@ -73,15 +73,15 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
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.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
||||
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
||||
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||
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.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
|
||||
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
|
||||
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=
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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}}`))
|
||||
|
||||
@ -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")
|
||||
|
||||
1
utils.go
1
utils.go
@ -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 {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user