Skip to content
Myr

gin_test.go

This file

Path

gin_test.go

1,197 lines · 28.8 KiB · Go

Last changed by

fix(engine): add default ReadHeaderTimeout to http.Server in Run methods (#4800)Ruben Paribefore adoptiond8f2d58

History of this file

Take it

The walk stopped after 200 commits: lines older than cf32d2d point at it.

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 1–48why, one step back
1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (8 "crypto/tls"9 "fmt"10 "html/template"11 "io"12 "net"13 "net/http"14 "net/http/httptest"15 "reflect"16 "strconv"17 "strings"18 "sync/atomic"19 "testing"20 "time"2122 "github.com/stretchr/testify/assert"23 "github.com/stretchr/testify/require"24 "golang.org/x/net/http2"25)2627func formatAsDate(t time.Time) string {28 year, month, day := t.Date()29 return fmt.Sprintf("%d/%02d/%02d", year, month, day)30}3132func setupHTMLFiles(t *testing.T, mode string, tls bool, loadMethod func(*Engine)) *httptest.Server {33 SetMode(mode)34 defer SetMode(TestMode)3536 var router *Engine37 captureOutput(t, func() {38 router = New()39 router.Delims("{[{", "}]}")40 router.SetFuncMap(template.FuncMap{41 "formatAsDate": formatAsDate,42 })43 loadMethod(router)44 router.GET("/test", func(c *Context) {45 c.HTML(http.StatusOK, "hello.tmpl", map[string]string{"name": "world"})46 })47 router.GET("/raw", func(c *Context) {48 c.HTML(http.StatusOK, "raw.tmpl", map[string]any{

ci(golangci-lint): update configuration and fix lint issues (#4247)Flc゛before adoptionc4287b1

line 49why, one step back
49 "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), //nolint:gofumpt

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 50–85why, one step back
50 })
51 })52 })5354 var ts *httptest.Server5556 if tls {57 ts = httptest.NewTLSServer(router)58 } else {59 ts = httptest.NewServer(router)60 }6162 return ts63}6465func TestLoadHTMLGlobDebugMode(t *testing.T) {66 ts := setupHTMLFiles(67 t,68 DebugMode,69 false,70 func(router *Engine) {71 router.LoadHTMLGlob("./testdata/template/*")72 },73 )74 defer ts.Close()7576 res, err := http.Get(ts.URL + "/test")77 if err != nil {78 t.Error(err)79 }8081 resp, _ := io.ReadAll(res.Body)82 assert.Equal(t, "<h1>Hello world</h1>", string(resp))83}8485func TestH2c(t *testing.T) {

refactor(context): replace hardcoded localhost IPs with constants (#4481)Paulo Henriquebefore adoption915e4c9

line 86why, one step back
86 ln, err := net.Listen("tcp", localhostIP+":0")

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 87–340why, one step back
87 if err != nil {
88 t.Error(err)89 }90 r := Default()91 r.UseH2C = true92 r.GET("/", func(c *Context) {93 c.String(200, "<h1>Hello world</h1>")94 })95 go func() {96 err := http.Serve(ln, r.Handler())97 if err != nil {98 t.Log(err)99 }100 }()101 defer ln.Close()102103 url := "http://" + ln.Addr().String() + "/"104105 httpClient := http.Client{106 Transport: &http2.Transport{107 AllowHTTP: true,108 DialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) {109 return net.Dial(netw, addr)110 },111 },112 }113114 res, err := httpClient.Get(url)115 if err != nil {116 t.Error(err)117 }118119 resp, _ := io.ReadAll(res.Body)120 assert.Equal(t, "<h1>Hello world</h1>", string(resp))121}122123func TestLoadHTMLGlobTestMode(t *testing.T) {124 ts := setupHTMLFiles(125 t,126 TestMode,127 false,128 func(router *Engine) {129 router.LoadHTMLGlob("./testdata/template/*")130 },131 )132 defer ts.Close()133134 res, err := http.Get(ts.URL + "/test")135 if err != nil {136 t.Error(err)137 }138139 resp, _ := io.ReadAll(res.Body)140 assert.Equal(t, "<h1>Hello world</h1>", string(resp))141}142143func TestLoadHTMLGlobReleaseMode(t *testing.T) {144 ts := setupHTMLFiles(145 t,146 ReleaseMode,147 false,148 func(router *Engine) {149 router.LoadHTMLGlob("./testdata/template/*")150 },151 )152 defer ts.Close()153154 res, err := http.Get(ts.URL + "/test")155 if err != nil {156 t.Error(err)157 }158159 resp, _ := io.ReadAll(res.Body)160 assert.Equal(t, "<h1>Hello world</h1>", string(resp))161}162163func TestLoadHTMLGlobUsingTLS(t *testing.T) {164 ts := setupHTMLFiles(165 t,166 DebugMode,167 true,168 func(router *Engine) {169 router.LoadHTMLGlob("./testdata/template/*")170 },171 )172 defer ts.Close()173174 // Use InsecureSkipVerify for avoiding `x509: certificate signed by unknown authority` error175 tr := &http.Transport{176 TLSClientConfig: &tls.Config{177 InsecureSkipVerify: true,178 },179 }180 client := &http.Client{Transport: tr}181 res, err := client.Get(ts.URL + "/test")182 if err != nil {183 t.Error(err)184 }185186 resp, _ := io.ReadAll(res.Body)187 assert.Equal(t, "<h1>Hello world</h1>", string(resp))188}189190func TestLoadHTMLGlobFromFuncMap(t *testing.T) {191 ts := setupHTMLFiles(192 t,193 DebugMode,194 false,195 func(router *Engine) {196 router.LoadHTMLGlob("./testdata/template/*")197 },198 )199 defer ts.Close()200201 res, err := http.Get(ts.URL + "/raw")202 if err != nil {203 t.Error(err)204 }205206 resp, _ := io.ReadAll(res.Body)207 assert.Equal(t, "Date: 2017/07/01", string(resp))208}209210func init() {211 SetMode(TestMode)212}213214func TestCreateEngine(t *testing.T) {215 router := New()216 assert.Equal(t, "/", router.basePath)217 assert.Equal(t, router.engine, router)218 assert.Empty(t, router.Handlers)219}220221func TestLoadHTMLFilesTestMode(t *testing.T) {222 ts := setupHTMLFiles(223 t,224 TestMode,225 false,226 func(router *Engine) {227 router.LoadHTMLFiles("./testdata/template/hello.tmpl", "./testdata/template/raw.tmpl")228 },229 )230 defer ts.Close()231232 res, err := http.Get(ts.URL + "/test")233 if err != nil {234 t.Error(err)235 }236237 resp, _ := io.ReadAll(res.Body)238 assert.Equal(t, "<h1>Hello world</h1>", string(resp))239}240241func TestLoadHTMLFilesDebugMode(t *testing.T) {242 ts := setupHTMLFiles(243 t,244 DebugMode,245 false,246 func(router *Engine) {247 router.LoadHTMLFiles("./testdata/template/hello.tmpl", "./testdata/template/raw.tmpl")248 },249 )250 defer ts.Close()251252 res, err := http.Get(ts.URL + "/test")253 if err != nil {254 t.Error(err)255 }256257 resp, _ := io.ReadAll(res.Body)258 assert.Equal(t, "<h1>Hello world</h1>", string(resp))259}260261func TestLoadHTMLFilesReleaseMode(t *testing.T) {262 ts := setupHTMLFiles(263 t,264 ReleaseMode,265 false,266 func(router *Engine) {267 router.LoadHTMLFiles("./testdata/template/hello.tmpl", "./testdata/template/raw.tmpl")268 },269 )270 defer ts.Close()271272 res, err := http.Get(ts.URL + "/test")273 if err != nil {274 t.Error(err)275 }276277 resp, _ := io.ReadAll(res.Body)278 assert.Equal(t, "<h1>Hello world</h1>", string(resp))279}280281func TestLoadHTMLFilesUsingTLS(t *testing.T) {282 ts := setupHTMLFiles(283 t,284 TestMode,285 true,286 func(router *Engine) {287 router.LoadHTMLFiles("./testdata/template/hello.tmpl", "./testdata/template/raw.tmpl")288 },289 )290 defer ts.Close()291292 // Use InsecureSkipVerify for avoiding `x509: certificate signed by unknown authority` error293 tr := &http.Transport{294 TLSClientConfig: &tls.Config{295 InsecureSkipVerify: true,296 },297 }298 client := &http.Client{Transport: tr}299 res, err := client.Get(ts.URL + "/test")300 if err != nil {301 t.Error(err)302 }303304 resp, _ := io.ReadAll(res.Body)305 assert.Equal(t, "<h1>Hello world</h1>", string(resp))306}307308func TestLoadHTMLFilesFuncMap(t *testing.T) {309 ts := setupHTMLFiles(310 t,311 TestMode,312 false,313 func(router *Engine) {314 router.LoadHTMLFiles("./testdata/template/hello.tmpl", "./testdata/template/raw.tmpl")315 },316 )317 defer ts.Close()318319 res, err := http.Get(ts.URL + "/raw")320 if err != nil {321 t.Error(err)322 }323324 resp, _ := io.ReadAll(res.Body)325 assert.Equal(t, "Date: 2017/07/01", string(resp))326}327328var tmplFS = http.Dir("testdata/template")329330func TestLoadHTMLFSTestMode(t *testing.T) {331 ts := setupHTMLFiles(332 t,333 TestMode,334 false,335 func(router *Engine) {336 router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl")337 },338 )339 defer ts.Close()340

test: fix lint failures (#4244)Siddhesh Mhadnakbefore adoptionda67cc1

line 341why, one step back
341 res, err := http.Get(ts.URL + "/test")

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 342–360why, one step back
342 if err != nil {
343 t.Error(err)344 }345346 resp, _ := io.ReadAll(res.Body)347 assert.Equal(t, "<h1>Hello world</h1>", string(resp))348}349350func TestLoadHTMLFSDebugMode(t *testing.T) {351 ts := setupHTMLFiles(352 t,353 DebugMode,354 false,355 func(router *Engine) {356 router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl")357 },358 )359 defer ts.Close()360

test: fix lint failures (#4244)Siddhesh Mhadnakbefore adoptionda67cc1

line 361why, one step back
361 res, err := http.Get(ts.URL + "/test")

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 362–380why, one step back
362 if err != nil {
363 t.Error(err)364 }365366 resp, _ := io.ReadAll(res.Body)367 assert.Equal(t, "<h1>Hello world</h1>", string(resp))368}369370func TestLoadHTMLFSReleaseMode(t *testing.T) {371 ts := setupHTMLFiles(372 t,373 ReleaseMode,374 false,375 func(router *Engine) {376 router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl")377 },378 )379 defer ts.Close()380

test: fix lint failures (#4244)Siddhesh Mhadnakbefore adoptionda67cc1

line 381why, one step back
381 res, err := http.Get(ts.URL + "/test")

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 382–407why, one step back
382 if err != nil {
383 t.Error(err)384 }385386 resp, _ := io.ReadAll(res.Body)387 assert.Equal(t, "<h1>Hello world</h1>", string(resp))388}389390func TestLoadHTMLFSUsingTLS(t *testing.T) {391 ts := setupHTMLFiles(392 t,393 TestMode,394 true,395 func(router *Engine) {396 router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl")397 },398 )399 defer ts.Close()400401 // Use InsecureSkipVerify for avoiding `x509: certificate signed by unknown authority` error402 tr := &http.Transport{403 TLSClientConfig: &tls.Config{404 InsecureSkipVerify: true,405 },406 }407 client := &http.Client{Transport: tr}

test: fix lint failures (#4244)Siddhesh Mhadnakbefore adoptionda67cc1

line 408why, one step back
408 res, err := client.Get(ts.URL + "/test")

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 409–427why, one step back
409 if err != nil {
410 t.Error(err)411 }412413 resp, _ := io.ReadAll(res.Body)414 assert.Equal(t, "<h1>Hello world</h1>", string(resp))415}416417func TestLoadHTMLFSFuncMap(t *testing.T) {418 ts := setupHTMLFiles(419 t,420 TestMode,421 false,422 func(router *Engine) {423 router.LoadHTMLFS(tmplFS, "hello.tmpl", "raw.tmpl")424 },425 )426 defer ts.Close()427

test: fix lint failures (#4244)Siddhesh Mhadnakbefore adoptionda67cc1

line 428why, one step back
428 res, err := http.Get(ts.URL + "/raw")

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 429–547why, one step back
429 if err != nil {
430 t.Error(err)431 }432433 resp, _ := io.ReadAll(res.Body)434 assert.Equal(t, "Date: 2017/07/01", string(resp))435}436437func TestAddRoute(t *testing.T) {438 router := New()439 router.addRoute(http.MethodGet, "/", HandlersChain{func(_ *Context) {}})440441 assert.Len(t, router.trees, 1)442 assert.NotNil(t, router.trees.get(http.MethodGet))443 assert.Nil(t, router.trees.get(http.MethodPost))444445 router.addRoute(http.MethodPost, "/", HandlersChain{func(_ *Context) {}})446447 assert.Len(t, router.trees, 2)448 assert.NotNil(t, router.trees.get(http.MethodGet))449 assert.NotNil(t, router.trees.get(http.MethodPost))450451 router.addRoute(http.MethodPost, "/post", HandlersChain{func(_ *Context) {}})452 assert.Len(t, router.trees, 2)453}454455func TestAddRouteFails(t *testing.T) {456 router := New()457 assert.Panics(t, func() { router.addRoute("", "/", HandlersChain{func(_ *Context) {}}) })458 assert.Panics(t, func() { router.addRoute(http.MethodGet, "a", HandlersChain{func(_ *Context) {}}) })459 assert.Panics(t, func() { router.addRoute(http.MethodGet, "/", HandlersChain{}) })460461 router.addRoute(http.MethodPost, "/post", HandlersChain{func(_ *Context) {}})462 assert.Panics(t, func() {463 router.addRoute(http.MethodPost, "/post", HandlersChain{func(_ *Context) {}})464 })465}466467func TestCreateDefaultRouter(t *testing.T) {468 router := Default()469 assert.Len(t, router.Handlers, 2)470}471472func TestNoRouteWithoutGlobalHandlers(t *testing.T) {473 var middleware0 HandlerFunc = func(c *Context) {}474 var middleware1 HandlerFunc = func(c *Context) {}475476 router := New()477478 router.NoRoute(middleware0)479 assert.Nil(t, router.Handlers)480 assert.Len(t, router.noRoute, 1)481 assert.Len(t, router.allNoRoute, 1)482 compareFunc(t, router.noRoute[0], middleware0)483 compareFunc(t, router.allNoRoute[0], middleware0)484485 router.NoRoute(middleware1, middleware0)486 assert.Len(t, router.noRoute, 2)487 assert.Len(t, router.allNoRoute, 2)488 compareFunc(t, router.noRoute[0], middleware1)489 compareFunc(t, router.allNoRoute[0], middleware1)490 compareFunc(t, router.noRoute[1], middleware0)491 compareFunc(t, router.allNoRoute[1], middleware0)492}493494func TestNoRouteWithGlobalHandlers(t *testing.T) {495 var middleware0 HandlerFunc = func(c *Context) {}496 var middleware1 HandlerFunc = func(c *Context) {}497 var middleware2 HandlerFunc = func(c *Context) {}498499 router := New()500 router.Use(middleware2)501502 router.NoRoute(middleware0)503 assert.Len(t, router.allNoRoute, 2)504 assert.Len(t, router.Handlers, 1)505 assert.Len(t, router.noRoute, 1)506507 compareFunc(t, router.Handlers[0], middleware2)508 compareFunc(t, router.noRoute[0], middleware0)509 compareFunc(t, router.allNoRoute[0], middleware2)510 compareFunc(t, router.allNoRoute[1], middleware0)511512 router.Use(middleware1)513 assert.Len(t, router.allNoRoute, 3)514 assert.Len(t, router.Handlers, 2)515 assert.Len(t, router.noRoute, 1)516517 compareFunc(t, router.Handlers[0], middleware2)518 compareFunc(t, router.Handlers[1], middleware1)519 compareFunc(t, router.noRoute[0], middleware0)520 compareFunc(t, router.allNoRoute[0], middleware2)521 compareFunc(t, router.allNoRoute[1], middleware1)522 compareFunc(t, router.allNoRoute[2], middleware0)523}524525func TestNoMethodWithoutGlobalHandlers(t *testing.T) {526 var middleware0 HandlerFunc = func(c *Context) {}527 var middleware1 HandlerFunc = func(c *Context) {}528529 router := New()530531 router.NoMethod(middleware0)532 assert.Empty(t, router.Handlers)533 assert.Len(t, router.noMethod, 1)534 assert.Len(t, router.allNoMethod, 1)535 compareFunc(t, router.noMethod[0], middleware0)536 compareFunc(t, router.allNoMethod[0], middleware0)537538 router.NoMethod(middleware1, middleware0)539 assert.Len(t, router.noMethod, 2)540 assert.Len(t, router.allNoMethod, 2)541 compareFunc(t, router.noMethod[0], middleware1)542 compareFunc(t, router.allNoMethod[0], middleware1)543 compareFunc(t, router.noMethod[1], middleware0)544 compareFunc(t, router.allNoMethod[1], middleware0)545}546547func TestRebuild404Handlers(t *testing.T) {

test(gin): resolve race conditions in integration tests (#4453)Wayne Akibefore adoptionf416d1e

lines 548–570why, one step back
548 var middleware0 HandlerFunc = func(c *Context) {}
549 var middleware1 HandlerFunc = func(c *Context) {}550551 router := New()552553 // Initially, allNoRoute should be nil554 assert.Nil(t, router.allNoRoute)555556 // Set NoRoute handlers557 router.NoRoute(middleware0)558 assert.Len(t, router.allNoRoute, 1)559 assert.Len(t, router.noRoute, 1)560 compareFunc(t, router.allNoRoute[0], middleware0)561562 // Add Use middleware should trigger rebuild404Handlers563 router.Use(middleware1)564 assert.Len(t, router.allNoRoute, 2)565 assert.Len(t, router.Handlers, 1)566 assert.Len(t, router.noRoute, 1)567568 // Global middleware should come first569 compareFunc(t, router.allNoRoute[0], middleware1)570 compareFunc(t, router.allNoRoute[1], middleware0)

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 571–745why, one step back
571}
572573func TestNoMethodWithGlobalHandlers(t *testing.T) {574 var middleware0 HandlerFunc = func(c *Context) {}575 var middleware1 HandlerFunc = func(c *Context) {}576 var middleware2 HandlerFunc = func(c *Context) {}577578 router := New()579 router.Use(middleware2)580581 router.NoMethod(middleware0)582 assert.Len(t, router.allNoMethod, 2)583 assert.Len(t, router.Handlers, 1)584 assert.Len(t, router.noMethod, 1)585586 compareFunc(t, router.Handlers[0], middleware2)587 compareFunc(t, router.noMethod[0], middleware0)588 compareFunc(t, router.allNoMethod[0], middleware2)589 compareFunc(t, router.allNoMethod[1], middleware0)590591 router.Use(middleware1)592 assert.Len(t, router.allNoMethod, 3)593 assert.Len(t, router.Handlers, 2)594 assert.Len(t, router.noMethod, 1)595596 compareFunc(t, router.Handlers[0], middleware2)597 compareFunc(t, router.Handlers[1], middleware1)598 compareFunc(t, router.noMethod[0], middleware0)599 compareFunc(t, router.allNoMethod[0], middleware2)600 compareFunc(t, router.allNoMethod[1], middleware1)601 compareFunc(t, router.allNoMethod[2], middleware0)602}603604func compareFunc(t *testing.T, a, b any) {605 sf1 := reflect.ValueOf(a)606 sf2 := reflect.ValueOf(b)607 if sf1.Pointer() != sf2.Pointer() {608 t.Error("different functions")609 }610}611612func TestListOfRoutes(t *testing.T) {613 router := New()614 router.GET("/favicon.ico", handlerTest1)615 router.GET("/", handlerTest1)616 group := router.Group("/users")617 {618 group.GET("/", handlerTest2)619 group.GET("/:id", handlerTest1)620 group.POST("/:id", handlerTest2)621 }622 router.Static("/static", ".")623624 list := router.Routes()625626 assert.Len(t, list, 7)627 assertRoutePresent(t, list, RouteInfo{628 Method: http.MethodGet,629 Path: "/favicon.ico",630 Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$",631 })632 assertRoutePresent(t, list, RouteInfo{633 Method: http.MethodGet,634 Path: "/",635 Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$",636 })637 assertRoutePresent(t, list, RouteInfo{638 Method: http.MethodGet,639 Path: "/users/",640 Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$",641 })642 assertRoutePresent(t, list, RouteInfo{643 Method: http.MethodGet,644 Path: "/users/:id",645 Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$",646 })647 assertRoutePresent(t, list, RouteInfo{648 Method: http.MethodPost,649 Path: "/users/:id",650 Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$",651 })652}653654func TestEngineHandleContext(t *testing.T) {655 r := New()656 r.GET("/", func(c *Context) {657 c.Request.URL.Path = "/v2"658 r.HandleContext(c)659 })660 v2 := r.Group("/v2")661 {662 v2.GET("/", func(c *Context) {})663 }664665 assert.NotPanics(t, func() {666 w := PerformRequest(r, http.MethodGet, "/")667 assert.Equal(t, 301, w.Code)668 })669}670671func TestEngineHandleContextManyReEntries(t *testing.T) {672 expectValue := 10000673674 var handlerCounter, middlewareCounter int64675676 r := New()677 r.Use(func(c *Context) {678 atomic.AddInt64(&middlewareCounter, 1)679 })680 r.GET("/:count", func(c *Context) {681 countStr := c.Param("count")682 count, err := strconv.Atoi(countStr)683 require.NoError(t, err)684685 n, err := c.Writer.Write([]byte("."))686 require.NoError(t, err)687 assert.Equal(t, 1, n)688689 switch {690 case count > 0:691 c.Request.URL.Path = "/" + strconv.Itoa(count-1)692 r.HandleContext(c)693 }694 }, func(c *Context) {695 atomic.AddInt64(&handlerCounter, 1)696 })697698 assert.NotPanics(t, func() {699 w := PerformRequest(r, http.MethodGet, "/"+strconv.Itoa(expectValue-1)) // include 0 value700 assert.Equal(t, 200, w.Code)701 assert.Equal(t, expectValue, w.Body.Len())702 })703704 assert.Equal(t, int64(expectValue), handlerCounter)705 assert.Equal(t, int64(expectValue), middlewareCounter)706}707708func TestEngineHandleContextPreventsMiddlewareReEntry(t *testing.T) {709 // given710 var handlerCounterV1, handlerCounterV2, middlewareCounterV1 int64711712 r := New()713 v1 := r.Group("/v1")714 {715 v1.Use(func(c *Context) {716 atomic.AddInt64(&middlewareCounterV1, 1)717 })718 v1.GET("/test", func(c *Context) {719 atomic.AddInt64(&handlerCounterV1, 1)720 c.Status(http.StatusOK)721 })722 }723724 v2 := r.Group("/v2")725 {726 v2.GET("/test", func(c *Context) {727 c.Request.URL.Path = "/v1/test"728 r.HandleContext(c)729 }, func(c *Context) {730 atomic.AddInt64(&handlerCounterV2, 1)731 })732 }733734 // when735 responseV1 := PerformRequest(r, "GET", "/v1/test")736 responseV2 := PerformRequest(r, "GET", "/v2/test")737738 // then739 assert.Equal(t, 200, responseV1.Code)740 assert.Equal(t, 200, responseV2.Code)741 assert.Equal(t, int64(2), handlerCounterV1)742 assert.Equal(t, int64(2), middlewareCounterV1)743 assert.Equal(t, int64(1), handlerCounterV2)744}745

test(engine): add regression tests for HandleContext with NoRoute (#4571)Abhiyan Khanalbefore adoptiond3ffc99

lines 746–817why, one step back
746func TestEngineHandleContextNoRouteWithGroupMiddleware(t *testing.T) {
747 // Scenario from issue #1848:748 // - Engine with no global middleware (gin.New())749 // - A group with middleware750 // - A route in that group751 // - NoRoute handler that redirects via HandleContext752 // The group middleware should run exactly once per HandleContext call,753 // not accumulate across redirects.754755 var middlewareCount, handlerCount int64756757 r := New()758 grp := r.Group("", func(c *Context) {759 atomic.AddInt64(&middlewareCount, 1)760 c.Next()761 })762 grp.GET("/target", func(c *Context) {763 atomic.AddInt64(&handlerCount, 1)764 c.String(http.StatusOK, "ok")765 })766767 r.NoRoute(func(c *Context) {768 c.Request.URL.Path = "/target"769 r.HandleContext(c)770 })771772 // Access a non-existent route to trigger NoRoute -> HandleContext773 w := PerformRequest(r, "GET", "/nonexistent")774 assert.Equal(t, http.StatusOK, w.Code)775 assert.Equal(t, "ok", w.Body.String())776 // Middleware and handler should each run exactly once777 assert.Equal(t, int64(1), atomic.LoadInt64(&middlewareCount))778 assert.Equal(t, int64(1), atomic.LoadInt64(&handlerCount))779}780781func TestEngineHandleContextNoRouteWithEngineMiddleware(t *testing.T) {782 // When engine middleware exists and NoRoute redirects via HandleContext,783 // verify the handlers run the expected number of times.784785 var engineMwCount, groupMwCount, handlerCount int64786787 r := New()788 r.Use(func(c *Context) {789 atomic.AddInt64(&engineMwCount, 1)790 c.Next()791 })792793 grp := r.Group("", func(c *Context) {794 atomic.AddInt64(&groupMwCount, 1)795 c.Next()796 })797 grp.GET("/target", func(c *Context) {798 atomic.AddInt64(&handlerCount, 1)799 c.String(http.StatusOK, "ok")800 })801802 r.NoRoute(func(c *Context) {803 c.Request.URL.Path = "/target"804 r.HandleContext(c)805 })806807 w := PerformRequest(r, "GET", "/nonexistent")808 assert.Equal(t, http.StatusOK, w.Code)809 assert.Equal(t, "ok", w.Body.String())810 // Handler and group middleware should each run once (from HandleContext)811 assert.Equal(t, int64(1), atomic.LoadInt64(&handlerCount))812 assert.Equal(t, int64(1), atomic.LoadInt64(&groupMwCount))813 // Engine middleware runs twice: once for the NoRoute chain, once for the HandleContext chain814 // This is expected behavior since HandleContext re-enters the full handler chain815 assert.Equal(t, int64(2), atomic.LoadInt64(&engineMwCount))816}817

feat(gin): add option to use escaped path (#4420)Aeddis Desauwbefore adoption771dcc6

lines 818–866why, one step back
818func TestEngineHandleContextUseEscapedPathPercentEncoded(t *testing.T) {
819 r := New()820 r.UseEscapedPath = true821 r.UnescapePathValues = false822823 r.GET("/v1/:path", func(c *Context) {824 // Path is Escaped, the %25 is not interpreted as %825 assert.Equal(t, "foo%252Fbar", c.Param("path"))826 c.Status(http.StatusOK)827 })828829 req := httptest.NewRequest(http.MethodGet, "/v1/foo%252Fbar", nil)830 w := httptest.NewRecorder()831 r.ServeHTTP(w, req)832}833834func TestEngineHandleContextUseRawPathPercentEncoded(t *testing.T) {835 r := New()836 r.UseRawPath = true837 r.UnescapePathValues = false838839 r.GET("/v1/:path", func(c *Context) {840 // Path is used, the %25 is interpreted as %841 assert.Equal(t, "foo%2Fbar", c.Param("path"))842 c.Status(http.StatusOK)843 })844845 req := httptest.NewRequest(http.MethodGet, "/v1/foo%252Fbar", nil)846 w := httptest.NewRecorder()847 r.ServeHTTP(w, req)848}849850func TestEngineHandleContextUseEscapedPathOverride(t *testing.T) {851 r := New()852 r.UseEscapedPath = true853 r.UseRawPath = true854 r.UnescapePathValues = false855856 r.GET("/v1/:path", func(c *Context) {857 assert.Equal(t, "foo%25bar", c.Param("path"))858 c.Status(http.StatusOK)859 })860861 assert.NotPanics(t, func() {862 w := PerformRequest(r, http.MethodGet, "/v1/foo%25bar")863 assert.Equal(t, 200, w.Code)864 })865}866

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 867–993why, one step back
867func TestPrepareTrustedCIRDsWith(t *testing.T) {
868 r := New()869870 // valid ipv4 cidr871 {872 expectedTrustedCIDRs := []*net.IPNet{parseCIDR("0.0.0.0/0")}873 err := r.SetTrustedProxies([]string{"0.0.0.0/0"})874875 require.NoError(t, err)876 assert.Equal(t, expectedTrustedCIDRs, r.trustedCIDRs)877 }878879 // invalid ipv4 cidr880 {881 err := r.SetTrustedProxies([]string{"192.168.1.33/33"})882883 require.Error(t, err)884 }885886 // valid ipv4 address887 {888 expectedTrustedCIDRs := []*net.IPNet{parseCIDR("192.168.1.33/32")}889890 err := r.SetTrustedProxies([]string{"192.168.1.33"})891892 require.NoError(t, err)893 assert.Equal(t, expectedTrustedCIDRs, r.trustedCIDRs)894 }895896 // invalid ipv4 address897 {898 err := r.SetTrustedProxies([]string{"192.168.1.256"})899900 require.Error(t, err)901 }902903 // valid ipv6 address904 {905 expectedTrustedCIDRs := []*net.IPNet{parseCIDR("2002:0000:0000:1234:abcd:ffff:c0a8:0101/128")}906 err := r.SetTrustedProxies([]string{"2002:0000:0000:1234:abcd:ffff:c0a8:0101"})907908 require.NoError(t, err)909 assert.Equal(t, expectedTrustedCIDRs, r.trustedCIDRs)910 }911912 // invalid ipv6 address913 {914 err := r.SetTrustedProxies([]string{"gggg:0000:0000:1234:abcd:ffff:c0a8:0101"})915916 require.Error(t, err)917 }918919 // valid ipv6 cidr920 {921 expectedTrustedCIDRs := []*net.IPNet{parseCIDR("::/0")}922 err := r.SetTrustedProxies([]string{"::/0"})923924 require.NoError(t, err)925 assert.Equal(t, expectedTrustedCIDRs, r.trustedCIDRs)926 }927928 // invalid ipv6 cidr929 {930 err := r.SetTrustedProxies([]string{"gggg:0000:0000:1234:abcd:ffff:c0a8:0101/129"})931932 require.Error(t, err)933 }934935 // valid combination936 {937 expectedTrustedCIDRs := []*net.IPNet{938 parseCIDR("::/0"),939 parseCIDR("192.168.0.0/16"),940 parseCIDR("172.16.0.1/32"),941 }942 err := r.SetTrustedProxies([]string{943 "::/0",944 "192.168.0.0/16",945 "172.16.0.1",946 })947948 require.NoError(t, err)949 assert.Equal(t, expectedTrustedCIDRs, r.trustedCIDRs)950 }951952 // invalid combination953 {954 err := r.SetTrustedProxies([]string{955 "::/0",956 "192.168.0.0/16",957 "172.16.0.256",958 })959960 require.Error(t, err)961 }962963 // nil value964 {965 err := r.SetTrustedProxies(nil)966967 assert.Nil(t, r.trustedCIDRs)968 require.NoError(t, err)969 }970}971972func parseCIDR(cidr string) *net.IPNet {973 _, parsedCIDR, err := net.ParseCIDR(cidr)974 if err != nil {975 fmt.Println(err)976 }977 return parsedCIDR978}979980func assertRoutePresent(t *testing.T, gotRoutes RoutesInfo, wantRoute RouteInfo) {981 for _, gotRoute := range gotRoutes {982 if gotRoute.Path == wantRoute.Path && gotRoute.Method == wantRoute.Method {983 assert.Regexp(t, wantRoute.Handler, gotRoute.Handler)984 return985 }986 }987 t.Errorf("route not found: %v", wantRoute)988}989990func handlerTest1(c *Context) {}991func handlerTest2(c *Context) {}992993func TestNewOptionFunc(t *testing.T) {

test: fix lint failures (#4244)Siddhesh Mhadnakbefore adoptionda67cc1

line 994why, one step back
994 fc := func(e *Engine) {

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 995–1026why, one step back
995 e.GET("/test1", handlerTest1)
996 e.GET("/test2", handlerTest2)997998 e.Use(func(c *Context) {999 c.Next()1000 })1001 }10021003 r := New(fc)10041005 routes := r.Routes()1006 assertRoutePresent(t, routes, RouteInfo{Path: "/test1", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest1"})1007 assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest2"})1008}10091010func TestWithOptionFunc(t *testing.T) {1011 r := New()10121013 r.With(func(e *Engine) {1014 e.GET("/test1", handlerTest1)1015 e.GET("/test2", handlerTest2)10161017 e.Use(func(c *Context) {1018 c.Next()1019 })1020 })10211022 routes := r.Routes()1023 assertRoutePresent(t, routes, RouteInfo{Path: "/test1", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest1"})1024 assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest2"})1025}1026

fix(engine): add default ReadHeaderTimeout to http.Server in Run methods (#4800)Ruben Paribefore adoptiond8f2d58

lines 1027–1046why, one step back
1027func TestReadHeaderTimeoutDefault(t *testing.T) {
1028 engine := New()1029 assert.Equal(t, defaultReadHeaderTimeout, engine.ReadHeaderTimeout)1030 assert.Equal(t, defaultReadHeaderTimeout, engine.getReadHeaderTimeout())1031}10321033func TestReadHeaderTimeoutCustom(t *testing.T) {1034 engine := New(func(e *Engine) {1035 e.ReadHeaderTimeout = 30 * time.Second1036 })1037 assert.Equal(t, 30*time.Second, engine.ReadHeaderTimeout)1038 assert.Equal(t, 30*time.Second, engine.getReadHeaderTimeout())1039}10401041func TestReadHeaderTimeoutZeroFallsBackToDefault(t *testing.T) {1042 engine := New()1043 engine.ReadHeaderTimeout = 01044 assert.Equal(t, defaultReadHeaderTimeout, engine.getReadHeaderTimeout())1045}1046

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 1047–1049why, one step back
1047type Birthday string
10481049func (b *Birthday) UnmarshalParam(param string) error {

ci(golangci-lint): update configuration and fix lint issues (#4247)Flc゛before adoptionc4287b1

line 1050why, one step back
1050 *b = Birthday(strings.ReplaceAll(param, "-", "/"))

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 1051–1079why, one step back
1051 return nil
1052}10531054func TestCustomUnmarshalStruct(t *testing.T) {1055 route := Default()1056 var request struct {1057 Birthday Birthday `form:"birthday"`1058 }1059 route.GET("/test", func(ctx *Context) {1060 _ = ctx.BindQuery(&request)1061 ctx.JSON(200, request.Birthday)1062 })1063 req := httptest.NewRequest(http.MethodGet, "/test?birthday=2000-01-01", nil)1064 w := httptest.NewRecorder()1065 route.ServeHTTP(w, req)1066 assert.Equal(t, 200, w.Code)1067 assert.Equal(t, `"2000/01/01"`, w.Body.String())1068}10691070// Test the fix for https://github.com/gin-gonic/gin/issues/40021071func TestMethodNotAllowedNoRoute(t *testing.T) {1072 g := New()1073 g.HandleMethodNotAllowed = true10741075 req := httptest.NewRequest(http.MethodGet, "/", nil)1076 resp := httptest.NewRecorder()1077 assert.NotPanics(t, func() { g.ServeHTTP(resp, req) })1078 assert.Equal(t, http.StatusNotFound, resp.Code)1079}

fix(gin): literal colon routes not working with engine.Handler() (#4415)Pawan Kalyanbefore adoption5fad976

lines 1080–1178why, one step back
1080
1081// Test the fix for https://github.com/gin-gonic/gin/pull/44151082func TestLiteralColonWithRun(t *testing.T) {1083 SetMode(TestMode)1084 router := New()10851086 router.GET(`/test\:action`, func(c *Context) {1087 c.JSON(http.StatusOK, H{"path": "literal_colon"})1088 })10891090 router.updateRouteTrees()10911092 w := httptest.NewRecorder()10931094 req, _ := http.NewRequest(http.MethodGet, "/test:action", nil)1095 router.ServeHTTP(w, req)10961097 assert.Equal(t, http.StatusOK, w.Code)1098 assert.Contains(t, w.Body.String(), "literal_colon")1099}11001101func TestLiteralColonWithDirectServeHTTP(t *testing.T) {1102 SetMode(TestMode)1103 router := New()11041105 router.GET(`/test\:action`, func(c *Context) {1106 c.JSON(http.StatusOK, H{"path": "literal_colon"})1107 })11081109 w := httptest.NewRecorder()1110 req, _ := http.NewRequest(http.MethodGet, "/test:action", nil)1111 router.ServeHTTP(w, req)11121113 assert.Equal(t, http.StatusOK, w.Code)1114 assert.Contains(t, w.Body.String(), "literal_colon")1115}11161117func TestLiteralColonWithHandler(t *testing.T) {1118 SetMode(TestMode)1119 router := New()11201121 router.GET(`/test\:action`, func(c *Context) {1122 c.JSON(http.StatusOK, H{"path": "literal_colon"})1123 })11241125 handler := router.Handler()11261127 w := httptest.NewRecorder()1128 req, _ := http.NewRequest(http.MethodGet, "/test:action", nil)1129 handler.ServeHTTP(w, req)11301131 assert.Equal(t, http.StatusOK, w.Code)1132 assert.Contains(t, w.Body.String(), "literal_colon")1133}11341135func TestLiteralColonWithHTTPServer(t *testing.T) {1136 SetMode(TestMode)1137 router := New()11381139 router.GET(`/test\:action`, func(c *Context) {1140 c.JSON(http.StatusOK, H{"path": "literal_colon"})1141 })11421143 router.GET("/test/:param", func(c *Context) {1144 c.JSON(http.StatusOK, H{"param": c.Param("param")})1145 })11461147 w := httptest.NewRecorder()1148 req, _ := http.NewRequest(http.MethodGet, "/test:action", nil)1149 router.ServeHTTP(w, req)11501151 assert.Equal(t, http.StatusOK, w.Code)1152 assert.Contains(t, w.Body.String(), "literal_colon")11531154 w2 := httptest.NewRecorder()1155 req2, _ := http.NewRequest(http.MethodGet, "/test/foo", nil)1156 router.ServeHTTP(w2, req2)11571158 assert.Equal(t, http.StatusOK, w2.Code)1159 assert.Contains(t, w2.Body.String(), "foo")1160}11611162// Test that updateRouteTrees is called only once1163func TestUpdateRouteTreesCalledOnce(t *testing.T) {1164 SetMode(TestMode)1165 router := New()11661167 router.GET(`/test\:action`, func(c *Context) {1168 c.String(http.StatusOK, "ok")1169 })11701171 for range 5 {1172 w := httptest.NewRecorder()1173 req, _ := http.NewRequest(http.MethodGet, "/test:action", nil)1174 router.ServeHTTP(w, req)1175 assert.Equal(t, http.StatusOK, w.Code)1176 assert.Equal(t, "ok", w.Body.String())1177 }1178}

feat(router): add QUERY method shortcut for RFC 10008 (#4830)Jia-ben00before adoption2a1a14f

lines 1179–1197why, one step back
1179
1180func TestRouterQueryMethod(t *testing.T) {1181 router := New()1182 router.QUERY("/test", func(c *Context) {1183 c.String(http.StatusOK, "query ok")1184 })11851186 w := httptest.NewRecorder()1187 req, _ := http.NewRequest("QUERY", "/test", nil)1188 router.ServeHTTP(w, req)1189 assert.Equal(t, http.StatusOK, w.Code)1190 assert.Equal(t, "query ok", w.Body.String())11911192 // Other methods should not match1193 w2 := httptest.NewRecorder()1194 req2, _ := http.NewRequest(http.MethodGet, "/test", nil)1195 router.ServeHTTP(w2, req2)1196 assert.Equal(t, http.StatusNotFound, w2.Code)1197}