Skip to content
Myr

routes_test.go

This file

Path

routes_test.go

969 lines · 30.0 KiB · Go

Last changed by

fix(tree): grow skippedNodes when pooled capacity is stale (#4852)HazyLabbefore adoptionea9fab9

History of this file

Take it

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	"fmt"9	"net/http"10	"net/http/httptest"11	"os"12	"path/filepath"13	"strings"14	"testing"1516	"github.com/stretchr/testify/assert"17	"github.com/stretchr/testify/require"18)1920type header struct {21	Key   string22	Value string23}2425// PerformRequest for testing gin router.26func PerformRequest(r http.Handler, method, path string, headers ...header) *httptest.ResponseRecorder {27	req := httptest.NewRequest(method, path, nil)28	for _, h := range headers {29		req.Header.Add(h.Key, h.Value)30	}31	w := httptest.NewRecorder()32	r.ServeHTTP(w, req)33	return w34}3536func testRouteOK(method string, t *testing.T) {37	passed := false38	passedAny := false39	r := New()40	r.Any("/test2", func(c *Context) {41		passedAny = true42	})43	r.Handle(method, "/test", func(c *Context) {44		passed = true45	})4647	w := PerformRequest(r, method, "/test")48	assert.True(t, passed)49	assert.Equal(t, http.StatusOK, w.Code)5051	PerformRequest(r, method, "/test2")52	assert.True(t, passedAny)53}5455// testRouteNotOK tests that a request with the wrong method returns a not found response.56func testRouteNotOK(method string, t *testing.T) {57	passed := false58	router := New()59	router.Handle(method, "/test_2", func(c *Context) {60		passed = true61	})6263	w := PerformRequest(router, method, "/test")6465	assert.False(t, passed)66	assert.Equal(t, http.StatusNotFound, w.Code)67}6869// testRouteNotOK2 tests that a request with the wrong method returns a method not allowed response.70func testRouteNotOK2(method string, t *testing.T) {71	passed := false72	router := New()73	router.HandleMethodNotAllowed = true74	var methodRoute string75	if method == http.MethodPost {76		methodRoute = http.MethodGet77	} else {78		methodRoute = http.MethodPost79	}80	router.Handle(methodRoute, "/test", func(c *Context) {81		passed = true82	})8384	w := PerformRequest(router, method, "/test")8586	assert.False(t, passed)87	assert.Equal(t, http.StatusMethodNotAllowed, w.Code)88}8990// TestRouteQuery tests that a QUERY route is invoked and can read the request91// body, which is the whole point of the method (RFC 10008).92func TestRouteQuery(t *testing.T) {93	type search struct {94		Term string `json:"term"`95	}9697	router := New()98	router.QUERY("/search", func(c *Context) {99		var body search100		require.NoError(t, c.ShouldBindJSON(&body))101		c.String(http.StatusOK, body.Term)102	})103104	req := httptest.NewRequest(MethodQuery, "/search", strings.NewReader(`{"term":"gin"}`))105	req.Header.Set("Content-Type", MIMEJSON)106	w := httptest.NewRecorder()107	router.ServeHTTP(w, req)108109	assert.Equal(t, http.StatusOK, w.Code)110	assert.Equal(t, "gin", w.Body.String())111}112113// TestRouteQueryRegisteredByAny documents that Any registers QUERY.114func TestRouteQueryRegisteredByAny(t *testing.T) {115	router := New()116	router.Any("/test", func(c *Context) {117		c.Status(http.StatusOK)118	})119120	w := PerformRequest(router, MethodQuery, "/test")121122	assert.Equal(t, http.StatusOK, w.Code)123}124125// TestQueryRoutesInterface tests that a router reached through IRoutes can126// still register a QUERY route via the IQueryRoutes assertion.127func TestQueryRoutesInterface(t *testing.T) {128	router := New()129130	var routes IRoutes = router.Group("/v1")131	queryRoutes, ok := routes.(IQueryRoutes)132	require.True(t, ok)133134	queryRoutes.QUERY("/search", func(c *Context) {135		c.Status(http.StatusOK)136	})137138	w := PerformRequest(router, MethodQuery, "/v1/search")139140	assert.Equal(t, http.StatusOK, w.Code)141}142143func TestRouterMethod(t *testing.T) {144	router := New()145	router.PUT("/hey2", func(c *Context) {146		c.String(http.StatusOK, "sup2")147	})148149	router.PUT("/hey", func(c *Context) {150		c.String(http.StatusOK, "called")151	})152153	router.PUT("/hey3", func(c *Context) {154		c.String(http.StatusOK, "sup3")155	})156157	w := PerformRequest(router, http.MethodPut, "/hey")158159	assert.Equal(t, http.StatusOK, w.Code)160	assert.Equal(t, "called", w.Body.String())161}162163func TestRouterGroupRouteOK(t *testing.T) {164	testRouteOK(http.MethodGet, t)165	testRouteOK(http.MethodPost, t)166	testRouteOK(http.MethodPut, t)167	testRouteOK(http.MethodPatch, t)168	testRouteOK(http.MethodHead, t)169	testRouteOK(http.MethodOptions, t)170	testRouteOK(http.MethodDelete, t)171	testRouteOK(http.MethodConnect, t)172	testRouteOK(http.MethodTrace, t)173	testRouteOK(MethodQuery, t)174}175176func TestRouteNotOK(t *testing.T) {177	testRouteNotOK(http.MethodGet, t)178	testRouteNotOK(http.MethodPost, t)179	testRouteNotOK(http.MethodPut, t)180	testRouteNotOK(http.MethodPatch, t)181	testRouteNotOK(http.MethodHead, t)182	testRouteNotOK(http.MethodOptions, t)183	testRouteNotOK(http.MethodDelete, t)184	testRouteNotOK(http.MethodConnect, t)185	testRouteNotOK(http.MethodTrace, t)186	testRouteNotOK(MethodQuery, t)187}188189func TestRouteNotOK2(t *testing.T) {190	testRouteNotOK2(http.MethodGet, t)191	testRouteNotOK2(http.MethodPost, t)192	testRouteNotOK2(http.MethodPut, t)193	testRouteNotOK2(http.MethodPatch, t)194	testRouteNotOK2(http.MethodHead, t)195	testRouteNotOK2(http.MethodOptions, t)196	testRouteNotOK2(http.MethodDelete, t)197	testRouteNotOK2(http.MethodConnect, t)198	testRouteNotOK2(http.MethodTrace, t)199	testRouteNotOK2(MethodQuery, t)200}201202func TestRouteRedirectTrailingSlash(t *testing.T) {203	router := New()204	router.RedirectFixedPath = false205	router.RedirectTrailingSlash = true206	router.GET("/path", func(c *Context) {})207	router.GET("/path2/", func(c *Context) {})208	router.POST("/path3", func(c *Context) {})209	router.PUT("/path4/", func(c *Context) {})210211	w := PerformRequest(router, http.MethodGet, "/path/")212	assert.Equal(t, "/path", w.Header().Get("Location"))213	assert.Equal(t, http.StatusMovedPermanently, w.Code)214215	w = PerformRequest(router, http.MethodGet, "/path2")216	assert.Equal(t, "/path2/", w.Header().Get("Location"))217	assert.Equal(t, http.StatusMovedPermanently, w.Code)218219	w = PerformRequest(router, http.MethodPost, "/path3/")220	assert.Equal(t, "/path3", w.Header().Get("Location"))221	assert.Equal(t, http.StatusTemporaryRedirect, w.Code)222223	w = PerformRequest(router, http.MethodPut, "/path4")224	assert.Equal(t, "/path4/", w.Header().Get("Location"))225	assert.Equal(t, http.StatusTemporaryRedirect, w.Code)226227	w = PerformRequest(router, http.MethodGet, "/path")228	assert.Equal(t, http.StatusOK, w.Code)229230	w = PerformRequest(router, http.MethodGet, "/path2/")231	assert.Equal(t, http.StatusOK, w.Code)232233	w = PerformRequest(router, http.MethodPost, "/path3")234	assert.Equal(t, http.StatusOK, w.Code)235236	w = PerformRequest(router, http.MethodPut, "/path4/")237	assert.Equal(t, http.StatusOK, w.Code)238239	w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "/api"})240	assert.Equal(t, "/api/path2/", w.Header().Get("Location"))241	assert.Equal(t, http.StatusMovedPermanently, w.Code)242243	w = PerformRequest(router, http.MethodGet, "/path2/", header{Key: "X-Forwarded-Prefix", Value: "/api/"})244	assert.Equal(t, http.StatusOK, w.Code)245246	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "../../api#?"})247	assert.Equal(t, "/api/path", w.Header().Get("Location"))248	assert.Equal(t, http.StatusMovedPermanently, w.Code)249250	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "../../api"})251	assert.Equal(t, "/api/path", w.Header().Get("Location"))252	assert.Equal(t, http.StatusMovedPermanently, w.Code)253254	w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "../../api"})255	assert.Equal(t, "/api/path2/", w.Header().Get("Location"))256	assert.Equal(t, http.StatusMovedPermanently, w.Code)257258	w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "/../../api"})259	assert.Equal(t, "/api/path2/", w.Header().Get("Location"))260	assert.Equal(t, http.StatusMovedPermanently, w.Code)261262	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "api/../../"})263	assert.Equal(t, "//path", w.Header().Get("Location"))264	assert.Equal(t, http.StatusMovedPermanently, w.Code)265266	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "api/../../../"})267	assert.Equal(t, "/path", w.Header().Get("Location"))268	assert.Equal(t, http.StatusMovedPermanently, w.Code)269270	w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "../../gin-gonic.com"})271	assert.Equal(t, "/gin-goniccom/path2/", w.Header().Get("Location"))272	assert.Equal(t, http.StatusMovedPermanently, w.Code)273274	w = PerformRequest(router, http.MethodGet, "/path2", header{Key: "X-Forwarded-Prefix", Value: "/../../gin-gonic.com"})275	assert.Equal(t, "/gin-goniccom/path2/", w.Header().Get("Location"))276	assert.Equal(t, http.StatusMovedPermanently, w.Code)277278	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "https://gin-gonic.com/#"})279	assert.Equal(t, "https/gin-goniccom/https/gin-goniccom/path", w.Header().Get("Location"))280	assert.Equal(t, http.StatusMovedPermanently, w.Code)281282	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "#api"})283	assert.Equal(t, "api/api/path", w.Header().Get("Location"))284	assert.Equal(t, http.StatusMovedPermanently, w.Code)285286	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "/nor-mal/#?a=1"})287	assert.Equal(t, "/nor-mal/a1/path", w.Header().Get("Location"))288	assert.Equal(t, http.StatusMovedPermanently, w.Code)289290	w = PerformRequest(router, http.MethodGet, "/path/", header{Key: "X-Forwarded-Prefix", Value: "/nor-mal/%2e%2e/"})291	assert.Equal(t, "/nor-mal/2e2e/path", w.Header().Get("Location"))292	assert.Equal(t, http.StatusMovedPermanently, w.Code)293294	router.RedirectTrailingSlash = false295296	w = PerformRequest(router, http.MethodGet, "/path/")297	assert.Equal(t, http.StatusNotFound, w.Code)298	w = PerformRequest(router, http.MethodGet, "/path2")299	assert.Equal(t, http.StatusNotFound, w.Code)300	w = PerformRequest(router, http.MethodPost, "/path3/")301	assert.Equal(t, http.StatusNotFound, w.Code)302	w = PerformRequest(router, http.MethodPut, "/path4")303	assert.Equal(t, http.StatusNotFound, w.Code)304}305306func TestRouteRedirectFixedPath(t *testing.T) {307	router := New()308	router.RedirectFixedPath = true309	router.RedirectTrailingSlash = false310311	router.GET("/path", func(c *Context) {})312	router.GET("/Path2", func(c *Context) {})313	router.POST("/PATH3", func(c *Context) {})314	router.POST("/Path4/", func(c *Context) {})315316	w := PerformRequest(router, http.MethodGet, "/PATH")317	assert.Equal(t, "/path", w.Header().Get("Location"))318	assert.Equal(t, http.StatusMovedPermanently, w.Code)319320	w = PerformRequest(router, http.MethodGet, "/path2")321	assert.Equal(t, "/Path2", w.Header().Get("Location"))322	assert.Equal(t, http.StatusMovedPermanently, w.Code)323324	w = PerformRequest(router, http.MethodPost, "/path3")325	assert.Equal(t, "/PATH3", w.Header().Get("Location"))326	assert.Equal(t, http.StatusTemporaryRedirect, w.Code)327328	w = PerformRequest(router, http.MethodPost, "/path4")329	assert.Equal(t, "/Path4/", w.Header().Get("Location"))330	assert.Equal(t, http.StatusTemporaryRedirect, w.Code)331}332333// TestRouteParamsByName tests that route parameters can be parsed by name.334func TestRouteParamsByName(t *testing.T) {335	name := ""336	lastName := ""337	wild := ""338	router := New()339	router.GET("/test/:name/:last_name/*wild", func(c *Context) {340		name = c.Params.ByName("name")341		lastName = c.Params.ByName("last_name")342		var ok bool343		wild, ok = c.Params.Get("wild")344345		assert.True(t, ok)346		assert.Equal(t, name, c.Param("name"))347		assert.Equal(t, lastName, c.Param("last_name"))348349		assert.Empty(t, c.Param("wtf"))350		assert.Empty(t, c.Params.ByName("wtf"))351352		wtf, ok := c.Params.Get("wtf")353		assert.Empty(t, wtf)354		assert.False(t, ok)355	})356357	w := PerformRequest(router, http.MethodGet, "/test/john/smith/is/super/great")358359	assert.Equal(t, http.StatusOK, w.Code)360	assert.Equal(t, "john", name)361	assert.Equal(t, "smith", lastName)362	assert.Equal(t, "/is/super/great", wild)363}364365// TestRouteParamsByNameWithExtraSlash tests that route parameters can be parsed by name even with extra slashes.366func TestRouteParamsByNameWithExtraSlash(t *testing.T) {367	name := ""368	lastName := ""369	wild := ""370	router := New()371	router.RemoveExtraSlash = true372	router.GET("/test/:name/:last_name/*wild", func(c *Context) {373		name = c.Params.ByName("name")374		lastName = c.Params.ByName("last_name")375		var ok bool376		wild, ok = c.Params.Get("wild")377378		assert.True(t, ok)379		assert.Equal(t, name, c.Param("name"))380		assert.Equal(t, lastName, c.Param("last_name"))381382		assert.Empty(t, c.Param("wtf"))383		assert.Empty(t, c.Params.ByName("wtf"))384385		wtf, ok := c.Params.Get("wtf")386		assert.Empty(t, wtf)387		assert.False(t, ok)388	})389390	w := PerformRequest(router, http.MethodGet, "//test//john//smith//is//super//great")391392	assert.Equal(t, http.StatusOK, w.Code)393	assert.Equal(t, "john", name)394	assert.Equal(t, "smith", lastName)395	assert.Equal(t, "/is/super/great", wild)396}397398// TestRouteParamsNotEmpty tests that context parameters will be set399// even if a route with params/wildcards is registered after the context400// initialisation (which happened in a previous requests).401func TestRouteParamsNotEmpty(t *testing.T) {402	name := ""403	lastName := ""404	wild := ""405	router := New()406407	w := PerformRequest(router, http.MethodGet, "/test/john/smith/is/super/great")408409	assert.Equal(t, http.StatusNotFound, w.Code)410411	router.GET("/test/:name/:last_name/*wild", func(c *Context) {412		name = c.Params.ByName("name")413		lastName = c.Params.ByName("last_name")414		var ok bool415		wild, ok = c.Params.Get("wild")416417		assert.True(t, ok)418		assert.Equal(t, name, c.Param("name"))419		assert.Equal(t, lastName, c.Param("last_name"))420421		assert.Empty(t, c.Param("wtf"))422		assert.Empty(t, c.Params.ByName("wtf"))423424		wtf, ok := c.Params.Get("wtf")425		assert.Empty(t, wtf)426		assert.False(t, ok)427	})428429	w = PerformRequest(router, http.MethodGet, "/test/john/smith/is/super/great")430431	assert.Equal(t, http.StatusOK, w.Code)432	assert.Equal(t, "john", name)433	assert.Equal(t, "smith", lastName)434	assert.Equal(t, "/is/super/great", wild)435}436437// TestRouteStaticFile tests that a static file is served correctly.438func TestRouteStaticFile(t *testing.T) {439	// SETUP file440	testRoot, _ := os.Getwd()441	f, err := os.CreateTemp(testRoot, "")442	if err != nil {443		t.Error(err)444	}445	defer os.Remove(f.Name())446	_, err = f.WriteString("Gin Web Framework")447	require.NoError(t, err)448	f.Close()449450	dir, filename := filepath.Split(f.Name())451452	// SETUP gin453	router := New()454	router.Static("/using_static", dir)455	router.StaticFile("/result", f.Name())456457	w := PerformRequest(router, http.MethodGet, "/using_static/"+filename)458	w2 := PerformRequest(router, http.MethodGet, "/result")459460	assert.Equal(t, w, w2)461	assert.Equal(t, http.StatusOK, w.Code)462	assert.Equal(t, "Gin Web Framework", w.Body.String())463	assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))464465	w3 := PerformRequest(router, http.MethodHead, "/using_static/"+filename)466	w4 := PerformRequest(router, http.MethodHead, "/result")467468	assert.Equal(t, w3, w4)469	assert.Equal(t, http.StatusOK, w3.Code)470}471472// TestRouteStaticFileFS tests that a static file from an http.FileSystem is served correctly.473func TestRouteStaticFileFS(t *testing.T) {474	// SETUP file475	testRoot, _ := os.Getwd()476	f, err := os.CreateTemp(testRoot, "")477	if err != nil {478		t.Error(err)479	}480	defer os.Remove(f.Name())481	_, err = f.WriteString("Gin Web Framework")482	require.NoError(t, err)483	f.Close()484485	dir, filename := filepath.Split(f.Name())486	// SETUP gin487	router := New()488	router.Static("/using_static", dir)489	router.StaticFileFS("/result_fs", filename, Dir(dir, false))490491	w := PerformRequest(router, http.MethodGet, "/using_static/"+filename)492	w2 := PerformRequest(router, http.MethodGet, "/result_fs")493494	assert.Equal(t, w, w2)495	assert.Equal(t, http.StatusOK, w.Code)496	assert.Equal(t, "Gin Web Framework", w.Body.String())497	assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))498499	w3 := PerformRequest(router, http.MethodHead, "/using_static/"+filename)500	w4 := PerformRequest(router, http.MethodHead, "/result_fs")501502	assert.Equal(t, w3, w4)503	assert.Equal(t, http.StatusOK, w3.Code)504}505506// TestRouteStaticListingDir tests that static directory listing is enabled when configured.507func TestRouteStaticListingDir(t *testing.T) {508	router := New()509	router.StaticFS("/", Dir("./", true))510511	w := PerformRequest(router, http.MethodGet, "/")512513	assert.Equal(t, http.StatusOK, w.Code)514	assert.Contains(t, w.Body.String(), "gin.go")515	assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))516}517518// TestRouteStaticNoListing tests that static directory listing is disabled by default.519func TestRouteStaticNoListing(t *testing.T) {520	router := New()521	router.Static("/", "./")522523	w := PerformRequest(router, http.MethodGet, "/")524525	assert.Equal(t, http.StatusNotFound, w.Code)526	assert.NotContains(t, w.Body.String(), "gin.go")527}528529func TestRouterMiddlewareAndStatic(t *testing.T) {530	router := New()531	static := router.Group("/", func(c *Context) {532		c.Writer.Header().Add("Last-Modified", "Mon, 02 Jan 2006 15:04:05 MST")533		c.Writer.Header().Add("Expires", "Mon, 02 Jan 2006 15:04:05 MST")534		c.Writer.Header().Add("X-GIN", "Gin Framework")535	})536	static.Static("/", "./")537538	w := PerformRequest(router, http.MethodGet, "/gin.go")539540	assert.Equal(t, http.StatusOK, w.Code)541	assert.Contains(t, w.Body.String(), "package gin")542	// Content-Type='text/plain; charset=utf-8' when go version <= 1.16,543	// else, Content-Type='text/x-go; charset=utf-8'544	assert.NotEmpty(t, w.Header().Get("Content-Type"))545	assert.NotEqual(t, "Mon, 02 Jan 2006 15:04:05 MST", w.Header().Get("Last-Modified"))546	assert.Equal(t, "Mon, 02 Jan 2006 15:04:05 MST", w.Header().Get("Expires"))547	assert.Equal(t, "Gin Framework", w.Header().Get("x-GIN"))548}549550func TestRouteNotAllowedEnabled(t *testing.T) {551	router := New()552	router.HandleMethodNotAllowed = true553	router.POST("/path", func(c *Context) {})554	w := PerformRequest(router, http.MethodGet, "/path")555	assert.Equal(t, http.StatusMethodNotAllowed, w.Code)556557	router.NoMethod(func(c *Context) {558		c.String(http.StatusTeapot, "responseText")559	})560	w = PerformRequest(router, http.MethodGet, "/path")561	assert.Equal(t, "responseText", w.Body.String())562	assert.Equal(t, http.StatusTeapot, w.Code)563}564565func TestRouteNotAllowedEnabled2(t *testing.T) {566	router := New()567	router.HandleMethodNotAllowed = true568	// add one methodTree to trees569	router.addRoute(http.MethodPost, "/", HandlersChain{func(_ *Context) {}})570	router.GET("/path2", func(c *Context) {})571	w := PerformRequest(router, http.MethodPost, "/path2")572	assert.Equal(t, http.StatusMethodNotAllowed, w.Code)573}574575func TestRouteNotAllowedEnabled3(t *testing.T) {576	router := New()577	router.HandleMethodNotAllowed = true578	router.GET("/path", func(c *Context) {})579	router.POST("/path", func(c *Context) {})580	w := PerformRequest(router, http.MethodPut, "/path")581	assert.Equal(t, http.StatusMethodNotAllowed, w.Code)582	allowed := w.Header().Get("Allow")583	assert.Contains(t, allowed, http.MethodGet)584	assert.Contains(t, allowed, http.MethodPost)585}586587func TestRouteNotAllowedDisabled(t *testing.T) {588	router := New()589	router.HandleMethodNotAllowed = false590	router.POST("/path", func(c *Context) {})591	w := PerformRequest(router, http.MethodGet, "/path")592	assert.Equal(t, http.StatusNotFound, w.Code)593594	router.NoMethod(func(c *Context) {595		c.String(http.StatusTeapot, "responseText")596	})597	w = PerformRequest(router, http.MethodGet, "/path")598	assert.Equal(t, "404 page not found", w.Body.String())599	assert.Equal(t, http.StatusNotFound, w.Code)600}601602func TestRouterNotFoundWithRemoveExtraSlash(t *testing.T) {603	router := New()604	router.RemoveExtraSlash = true605	router.GET("/path", func(c *Context) {})606	router.GET("/", func(c *Context) {})607608	testRoutes := []struct {609		route    string610		code     int611		location string612	}{613		{"/../path", http.StatusOK, ""},    // CleanPath614		{"/nope", http.StatusNotFound, ""}, // NotFound615	}616	for _, tr := range testRoutes {617		w := PerformRequest(router, http.MethodGet, tr.route)618		assert.Equal(t, tr.code, w.Code)619		if w.Code != http.StatusNotFound {620			assert.Equal(t, tr.location, w.Header().Get("Location"))621		}622	}623}624625func TestRouterNotFound(t *testing.T) {626	router := New()627	router.RedirectFixedPath = true628	router.GET("/path", func(c *Context) {})629	router.GET("/dir/", func(c *Context) {})630	router.GET("/", func(c *Context) {})631632	testRoutes := []struct {633		route    string634		code     int635		location string636	}{637		{"/path/", http.StatusMovedPermanently, "/path"},   // TSR -/638		{"/dir", http.StatusMovedPermanently, "/dir/"},     // TSR +/639		{"/PATH", http.StatusMovedPermanently, "/path"},    // Fixed Case640		{"/DIR/", http.StatusMovedPermanently, "/dir/"},    // Fixed Case641		{"/PATH/", http.StatusMovedPermanently, "/path"},   // Fixed Case -/642		{"/DIR", http.StatusMovedPermanently, "/dir/"},     // Fixed Case +/643		{"/../path", http.StatusMovedPermanently, "/path"}, // Without CleanPath644		{"/nope", http.StatusNotFound, ""},                 // NotFound645	}646	for _, tr := range testRoutes {647		w := PerformRequest(router, http.MethodGet, tr.route)648		assert.Equal(t, tr.code, w.Code)649		if w.Code != http.StatusNotFound {650			assert.Equal(t, tr.location, w.Header().Get("Location"))651		}652	}653654	// Test custom not found handler655	var notFound bool656	router.NoRoute(func(c *Context) {657		c.AbortWithStatus(http.StatusNotFound)658		notFound = true659	})660	w := PerformRequest(router, http.MethodGet, "/nope")661	assert.Equal(t, http.StatusNotFound, w.Code)662	assert.True(t, notFound)663664	// Test other method than GET (want 307 instead of 301)665	router.PATCH("/path", func(c *Context) {})666	w = PerformRequest(router, http.MethodPatch, "/path/")667	assert.Equal(t, http.StatusTemporaryRedirect, w.Code)668	assert.Equal(t, "map[Location:[/path]]", fmt.Sprint(w.Header()))669670	// Test special case where no node for the prefix "/" exists671	router = New()672	router.GET("/a", func(c *Context) {})673	w = PerformRequest(router, http.MethodGet, "/")674	assert.Equal(t, http.StatusNotFound, w.Code)675676	// Reproduction test for the bug of issue #2843677	router = New()678	router.NoRoute(func(c *Context) {679		if c.Request.RequestURI == "/login" {680			c.String(http.StatusOK, "login")681		}682	})683	router.GET("/logout", func(c *Context) {684		c.String(http.StatusOK, "logout")685	})686	w = PerformRequest(router, http.MethodGet, "/login")687	assert.Equal(t, "login", w.Body.String())688	w = PerformRequest(router, http.MethodGet, "/logout")689	assert.Equal(t, "logout", w.Body.String())690}691692func TestRouterStaticFSNotFound(t *testing.T) {693	router := New()694	router.StaticFS("/", http.FileSystem(http.Dir("/thisreallydoesntexist/")))695	router.NoRoute(func(c *Context) {696		c.String(http.StatusNotFound, "non existent")697	})698699	w := PerformRequest(router, http.MethodGet, "/nonexistent")700	assert.Equal(t, "non existent", w.Body.String())701702	w = PerformRequest(router, http.MethodHead, "/nonexistent")703	assert.Equal(t, "non existent", w.Body.String())704}705706func TestRouterStaticFSFileNotFound(t *testing.T) {707	router := New()708709	router.StaticFS("/", http.FileSystem(http.Dir(".")))710711	assert.NotPanics(t, func() {712		PerformRequest(router, http.MethodGet, "/nonexistent")713	})714}715716// TestMiddlewareCalledOnceByRouterStaticFSNotFound reproduces the bug reported in issue #1805.717func TestMiddlewareCalledOnceByRouterStaticFSNotFound(t *testing.T) {718	router := New()719720	// Middleware must be called just only once by per request.721	middlewareCalledNum := 0722	router.Use(func(c *Context) {723		middlewareCalledNum++724	})725726	router.StaticFS("/", http.FileSystem(http.Dir("/thisreallydoesntexist/")))727728	// First access729	PerformRequest(router, http.MethodGet, "/nonexistent")730	assert.Equal(t, 1, middlewareCalledNum)731732	// Second access733	PerformRequest(router, http.MethodHead, "/nonexistent")734	assert.Equal(t, 2, middlewareCalledNum)735}736737func TestRouteRawPath(t *testing.T) {738	route := New()739	route.UseRawPath = true740741	route.POST("/project/:name/build/:num", func(c *Context) {742		name := c.Params.ByName("name")743		num := c.Params.ByName("num")744745		assert.Equal(t, name, c.Param("name"))746		assert.Equal(t, num, c.Param("num"))747748		assert.Equal(t, "Some/Other/Project", name)749		assert.Equal(t, "222", num)750	})751752	w := PerformRequest(route, http.MethodPost, "/project/Some%2FOther%2FProject/build/222")753	assert.Equal(t, http.StatusOK, w.Code)754}755756func TestRouteRawPathNoUnescape(t *testing.T) {757	route := New()758	route.UseRawPath = true759	route.UnescapePathValues = false760761	route.POST("/project/:name/build/:num", func(c *Context) {762		name := c.Params.ByName("name")763		num := c.Params.ByName("num")764765		assert.Equal(t, name, c.Param("name"))766		assert.Equal(t, num, c.Param("num"))767768		assert.Equal(t, "Some%2FOther%2FProject", name)769		assert.Equal(t, "333", num)770	})771772	w := PerformRequest(route, http.MethodPost, "/project/Some%2FOther%2FProject/build/333")773	assert.Equal(t, http.StatusOK, w.Code)774}775776func TestRouteServeErrorWithWriteHeader(t *testing.T) {777	route := New()778	route.Use(func(c *Context) {779		c.Status(http.StatusMisdirectedRequest)780		c.Next()781	})782783	w := PerformRequest(route, http.MethodGet, "/NotFound")784	assert.Equal(t, http.StatusMisdirectedRequest, w.Code)785	assert.Equal(t, 0, w.Body.Len())786}787788func TestRouteContextHoldsFullPath(t *testing.T) {789	router := New()790791	// Test routes792	routes := []string{793		"/simple",794		"/project/:name",795		"/",796		"/news/home",797		"/news",798		"/simple-two/one",799		"/simple-two/one-two",800		"/project/:name/build/*params",801		"/project/:name/bui",802		"/user/:id/status",803		"/user/:id",804		"/user/:id/profile",805	}806807	for _, route := range routes {808		actualRoute := route809		router.GET(route, func(c *Context) {810			// For each defined route context should contain its full path811			assert.Equal(t, actualRoute, c.FullPath())812			c.AbortWithStatus(http.StatusOK)813		})814	}815816	for _, route := range routes {817		w := PerformRequest(router, http.MethodGet, route)818		assert.Equal(t, http.StatusOK, w.Code)819	}820821	// Test not found822	router.Use(func(c *Context) {823		// For not found routes full path is empty824		assert.Empty(t, c.FullPath())825	})826827	w := PerformRequest(router, http.MethodGet, "/not-found")828	assert.Equal(t, http.StatusNotFound, w.Code)829}830831func TestEngineHandleMethodNotAllowedCornerCase(t *testing.T) {832	r := New()833	r.HandleMethodNotAllowed = true834835	base := r.Group("base")836	base.GET("/metrics", handlerTest1)837838	v1 := base.Group("v1")839840	v1.GET("/:id/devices", handlerTest1)841	v1.GET("/user/:id/groups", handlerTest1)842843	v1.GET("/orgs/:id", handlerTest1)844	v1.DELETE("/orgs/:id", handlerTest1)845846	w := PerformRequest(r, http.MethodGet, "/base/v1/user/groups")847	assert.Equal(t, http.StatusNotFound, w.Code)848}849850func TestLateRouteRegistrationSkippedNodes(t *testing.T) {851	router := New()852	router.HandleMethodNotAllowed = true853	router.GET("/a", func(c *Context) { c.Status(http.StatusOK) })854855	w := PerformRequest(router, http.MethodGet, "/a")856	if w.Code != http.StatusOK {857		t.Fatalf("warmup status = %d, want 200", w.Code)858	}859860	h := func(c *Context) {}861	router.GET("/x/y/z/w", h)862	router.GET("/x/y/:id/w", h)863	router.GET("/x/:id/z/w", h)864	router.GET("/:id/y/z/w", h)865866	req := httptest.NewRequest(http.MethodPost, "/x/y/z/w/extra", nil)867	w = httptest.NewRecorder()868	router.ServeHTTP(w, req)869	if w.Code != http.StatusNotFound {870		t.Fatalf("status = %d, want 404", w.Code)871	}872}873874// TestIssue4818_skippedNodesOverflow_Panic reproduces the panic from issue #4818:875// with HandleMethodNotAllowed enabled, getValue is called once per method tree876// reusing the same c.skippedNodes stack without resetting it, so residue877// accumulates until the reslice exceeds the capacity (engine.maxSections).878// The request must not panic and must fall through to the normal 404 path879// (the path genuinely matches no route, so 405 is not applicable here).880func TestIssue4818_skippedNodesOverflow_Panic(t *testing.T) {881	router := New()882	router.HandleMethodNotAllowed = true883884	h := func(c *Context) {}885	router.OPTIONS("/:p0/:p1/a/:p2", h)886	router.GET("/:p0/:p1/a/:p2", h)887	router.PATCH("/b/:p0/:p1/c", h)888	router.DELETE("/b/:p0/:p1/d/:p3", h)889	router.GET("/b/:p0/:p1/e/f", h)890	router.POST("/b/:p0/:p1/g/:p4/h", h)891	router.OPTIONS("/b/:p0/:p1/g/:p4/h", h)892	router.DELETE("/b/cache", h)893	router.GET("/b/clients/:p1/g", h)894	router.POST("/b/clients/:p1/g", h)895	router.PATCH("/b/clients/:p1/g/:p4", h)896	router.OPTIONS("/b/clients/:p1/g/:p4", h)897898	req := httptest.NewRequest(http.MethodPost, "/b/clients/42", nil)899	w := httptest.NewRecorder()900	router.ServeHTTP(w, req)901902	// Must not panic; path matches no route, so 404 is the correct outcome.903	if w.Code != http.StatusNotFound {904		t.Fatalf("expected 404, got %d (a panic would have aborted the test)", w.Code)905	}906}907908// TestIssue4818_MethodNotAllowedStillWorks verifies the HandleMethodNotAllowed909// loop still produces a correct 405 with an Allow header after the fix, i.e.910// the reset does not break the loop across multiple method trees.911func TestIssue4818_MethodNotAllowedStillWorks(t *testing.T) {912	router := New()913	router.HandleMethodNotAllowed = true914915	h := func(c *Context) {}916	router.OPTIONS("/:p0/:p1/a/:p2", h)917	router.GET("/:p0/:p1/a/:p2", h)918	router.PATCH("/b/:p0/:p1/c", h)919	router.DELETE("/b/:p0/:p1/d/:p3", h)920	router.GET("/b/:p0/:p1/e/f", h)921	router.POST("/b/:p0/:p1/g/:p4/h", h)922	router.OPTIONS("/b/:p0/:p1/g/:p4/h", h)923	router.DELETE("/b/cache", h)924	router.GET("/b/clients/:p1/g", h)925	router.POST("/b/clients/:p1/g", h)926	router.PATCH("/b/clients/:p1/g/:p4", h)927	router.OPTIONS("/b/clients/:p1/g/:p4", h)928929	// PATCH /b/clients/42/g is registered under GET but not under PATCH930	// -> HandleMethodNotAllowed should yield 405 with an Allow header.931	req := httptest.NewRequest(http.MethodPatch, "/b/clients/42/g", nil)932	w := httptest.NewRecorder()933	router.ServeHTTP(w, req)934935	if w.Code != http.StatusMethodNotAllowed {936		t.Fatalf("expected 405, got %d", w.Code)937	}938	allow := w.Header().Get("Allow")939	if allow == "" {940		t.Fatal("expected Allow header to be set for 405")941	}942}943944// TestIssue4818_MethodNotAllowedManyTrees stresses the loop across many945// method trees to make sure the skipped-nodes accumulator can never overflow.946func TestIssue4818_MethodNotAllowedManyTrees(t *testing.T) {947	router := New()948	router.HandleMethodNotAllowed = true949950	h := func(c *Context) {}951	for _, m := range []string{952		http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete,953		http.MethodPatch, http.MethodOptions, http.MethodHead, http.MethodConnect,954		http.MethodTrace,955	} {956		router.Handle(m, "/:p0/:p1/a/:p2", h)957		router.Handle(m, "/s/:p0/:p1/:p2/:p3/:p4/:p5/d", h)958	}959	// GET route so that a POST to a GET-only path yields 405960	router.GET("/only-get", h)961962	req := httptest.NewRequest(http.MethodPost, "/only-get", nil)963	w := httptest.NewRecorder()964	router.ServeHTTP(w, req)965966	if w.Code != http.StatusMethodNotAllowed {967		t.Fatalf("expected 405, got %d", w.Code)968	}969}