{"repo":"gin","file":"Makefile","line":1,"symbol":"GO","kind":"variable","lang":"make","code":"GO ?= go"} {"repo":"gin","file":"Makefile","line":2,"symbol":"GOFMT","kind":"variable","lang":"make","code":"GOFMT ?= gofmt \"-s\""} {"repo":"gin","file":"Makefile","line":3,"symbol":"GO_VERSION","kind":"variable","lang":"make","code":"GO_VERSION=$(shell $(GO) version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f2)"} {"repo":"gin","file":"Makefile","line":4,"symbol":"PACKAGES","kind":"variable","lang":"make","code":"PACKAGES ?= $(shell $(GO) list ./...)"} {"repo":"gin","file":"Makefile","line":5,"symbol":"VETPACKAGES","kind":"variable","lang":"make","code":"VETPACKAGES ?= $(shell $(GO) list ./... | grep -v /examples/)"} {"repo":"gin","file":"Makefile","line":6,"symbol":"GOFILES","kind":"variable","lang":"make","code":"GOFILES := $(shell find . -name \"*.go\")"} {"repo":"gin","file":"Makefile","line":7,"symbol":"TESTFOLDER","kind":"variable","lang":"make","code":"TESTFOLDER := $(shell $(GO) list ./... | grep -E 'gin$$|ginS$$|binding$$|render$$' | grep -v examples)"} {"repo":"gin","file":"Makefile","line":8,"symbol":"TESTTAGS","kind":"variable","lang":"make","code":"TESTTAGS ?= \"\""} {"repo":"gin","file":"Makefile","line":10,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: test"} {"repo":"gin","file":"Makefile","line":12,"symbol":"test","kind":"target","lang":"make","code":"test:\n\techo \"mode: count\" > coverage.out\n\tfor d in $(TESTFOLDER); do \\\n\t\tif [ -n \"$(TESTTAGS)\" ]; then \\\n\t\t\t$(GO) test $(TESTTAGS) -v -covermode=count -coverprofile=profile.out $$d > tmp.out; \\\n\t\telse \\\n\t\t\t$(GO) test -v -covermode=count -coverprofile=profile.out $$d > tmp.out; \\\n\t\tfi; \\\n\t\tcat tmp.out; \\\n\t\tif grep -q \"^--- FAIL\" tmp.out; then \\\n\t\t\trm tmp.out; \\\n\t\t\texit 1; \\\n\t\telif grep -q \"build failed\" tmp.out; then \\\n\t\t\trm tmp.out; \\\n\t\t\texit 1; \\\n\t\telif grep -q \"setup failed\" tmp.out; then \\\n\t\t\trm tmp.out; \\\n\t\t\texit 1; \\\n\t\tfi; \\\n\t\tif [ -f profile.out ]; then \\\n\t\t\tcat profile.out | grep -v \"mode:\" >> coverage.out; \\\n\t\t\trm profile.out; \\\n\t\tfi; \\\n\tdone"} {"repo":"gin","file":"Makefile","line":37,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: fmt"} {"repo":"gin","file":"Makefile","line":39,"symbol":"fmt","kind":"target","lang":"make","code":"fmt:\n\t$(GOFMT) -w $(GOFILES)"} {"repo":"gin","file":"Makefile","line":42,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: fmt-check"} {"repo":"gin","file":"Makefile","line":44,"symbol":"fmt-check","kind":"target","lang":"make","code":"fmt-check:\n\t@diff=$$($(GOFMT) -d $(GOFILES)); \\\n\tif [ -n \"$$diff\" ]; then \\\n\t\techo \"Please run 'make fmt' and commit the result:\"; \\\n\t\techo \"$${diff}\"; \\\n\t\texit 1; \\\n\tfi;"} {"repo":"gin","file":"Makefile","line":52,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: vet"} {"repo":"gin","file":"Makefile","line":54,"symbol":"vet","kind":"target","lang":"make","code":"vet:\n\t$(GO) vet $(VETPACKAGES)"} {"repo":"gin","file":"Makefile","line":57,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: lint"} {"repo":"gin","file":"Makefile","line":59,"symbol":"lint","kind":"target","lang":"make","code":"lint:\n\t@hash golint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \\\n\t\t$(GO) get -u golang.org/x/lint/golint; \\\n\tfi\n\tfor PKG in $(PACKAGES); do golint -set_exit_status $$PKG || exit 1; done;"} {"repo":"gin","file":"Makefile","line":65,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: misspell"} {"repo":"gin","file":"Makefile","line":67,"symbol":"misspell","kind":"target","lang":"make","code":"misspell:\n\t@hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \\\n\t\t$(GO) get -u github.com/client9/misspell/cmd/misspell; \\\n\tfi\n\tmisspell -w $(GOFILES)"} {"repo":"gin","file":"Makefile","line":73,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: misspell-check"} {"repo":"gin","file":"Makefile","line":75,"symbol":"misspell-check","kind":"target","lang":"make","code":"misspell-check:\n\t@hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \\\n\t\t$(GO) get -u github.com/client9/misspell/cmd/misspell; \\\n\tfi\n\tmisspell -error $(GOFILES)"} {"repo":"gin","file":"Makefile","line":81,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: tools"} {"repo":"gin","file":"Makefile","line":83,"symbol":"tools","kind":"target","lang":"make","code":"tools:\n\t@if [ $(GO_VERSION) -gt 15 ]; then \\\n\t\t$(GO) install golang.org/x/lint/golint@latest; \\\n\t\t$(GO) install github.com/client9/misspell/cmd/misspell@latest; \\\n\telif [ $(GO_VERSION) -lt 16 ]; then \\\n\t\t$(GO) install golang.org/x/lint/golint; \\\n\t\t$(GO) install github.com/client9/misspell/cmd/misspell; \\\n\tfi"} {"repo":"gin","file":"Makefile","line":92,"symbol":".PHONY","kind":"target","lang":"make","code":".PHONY: help"} {"repo":"gin","file":"Makefile","line":94,"symbol":"help","kind":"target","lang":"make","code":"help:\n\t@echo ''\n\t@echo 'Usage:'\n\t@echo ' make [target]'\n\t@echo ''\n\t@echo 'Targets:'\n\t@awk '/^[a-zA-Z\\-\\0-9]+:/ { \\\n\thelpMessage = match(lastLine, /^# (.*)/); \\\n\t\tif (helpMessage) { \\\n\t\t\thelpCommand = substr($$1, 0, index($$1, \":\")-1); \\\n\t\t\thelpMessage = substr(lastLine, RSTART + 2, RLENGTH); \\\n\t\t\tprintf \" - \\033[36m%-20s\\033[0m %s\\n\", helpCommand, helpMessage; \\\n\t\t} \\\n\t} \\\n\t{ lastLine = $$0 }' $(MAKEFILE_LIST)"} {"repo":"gin","file":"Makefile","line":110,"symbol":".DEFAULT_GOAL","kind":"variable","lang":"make","code":".DEFAULT_GOAL := help"} {"repo":"gin","file":"auth.go","line":17,"symbol":"AuthUserKey","kind":"constant","lang":"go","doc":"AuthUserKey is the cookie name for user credential in basic auth.","code":"AuthUserKey = \"user\""} {"repo":"gin","file":"auth.go","line":20,"symbol":"AuthProxyUserKey","kind":"constant","lang":"go","doc":"AuthProxyUserKey is the cookie name for proxy_user credential in basic auth for proxy.","code":"AuthProxyUserKey = \"proxy_user\""} {"repo":"gin","file":"auth.go","line":23,"symbol":"Accounts","kind":"type","lang":"go","doc":"Accounts defines a key/value for user/pass list of authorized logins.","code":"type Accounts map[string]string"} {"repo":"gin","file":"auth.go","line":25,"symbol":"authPair","kind":"type","lang":"go","code":"type authPair struct {\n\tvalue string\n\tuser string\n}"} {"repo":"gin","file":"auth.go","line":30,"symbol":"authPairs","kind":"type","lang":"go","code":"type authPairs []authPair"} {"repo":"gin","file":"auth.go","line":32,"symbol":"searchCredential","kind":"method","lang":"go","code":"func (a authPairs) searchCredential(authValue string) (string, bool) {\n\tif authValue == \"\" {\n\t\treturn \"\", false\n\t}\n\tfor _, pair := range a {\n\t\tif subtle.ConstantTimeCompare(bytesconv.StringToBytes(pair.value), bytesconv.StringToBytes(authValue)) == 1 {\n\t\t\treturn pair.user, true\n\t\t}\n\t}\n\treturn \"\", false\n}"} {"repo":"gin","file":"auth.go","line":48,"symbol":"BasicAuthForRealm","kind":"function","lang":"go","doc":"BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where the key is the user name and the value is the password, as well as the name of the Realm. If the realm is empty, \"Authorization Required\" will be used by default. (see http://tools.ietf.org/html/rfc2617#section-1.2)","code":"func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {\n\tif realm == \"\" {\n\t\trealm = \"Authorization Required\"\n\t}\n\trealm = \"Basic realm=\" + strconv.Quote(realm)\n\tpairs := processAccounts(accounts)\n\treturn func(c *Context) {\n\t\t// Search user in the slice of allowed credentials\n\t\tuser, found := pairs.searchCredential(c.requestHeader(\"Authorization\"))\n\t\tif !found {\n\t\t\t// Credentials doesn't match, we return 401 and abort handlers chain.\n\t\t\tc.Header(\"WWW-Authenticate\", realm)\n\t\t\tc.AbortWithStatus(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\t// The user credentials was found, set user's id to key AuthUserKey in this context, the user's id can be read later using\n\t\t// c.MustGet(gin.AuthUserKey).\n\t\tc.Set(AuthUserKey, user)\n\t}\n}"} {"repo":"gin","file":"auth.go","line":72,"symbol":"BasicAuth","kind":"function","lang":"go","doc":"BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where the key is the user name and the value is the password.","code":"func BasicAuth(accounts Accounts) HandlerFunc {\n\treturn BasicAuthForRealm(accounts, \"\")\n}"} {"repo":"gin","file":"auth.go","line":76,"symbol":"processAccounts","kind":"function","lang":"go","code":"func processAccounts(accounts Accounts) authPairs {\n\tlength := len(accounts)\n\tassert1(length > 0, \"Empty list of authorized credentials\")\n\tpairs := make(authPairs, 0, length)\n\tfor user, password := range accounts {\n\t\tassert1(user != \"\", \"User can not be empty\")\n\t\tvalue := authorizationHeader(user, password)\n\t\tpairs = append(pairs, authPair{\n\t\t\tvalue: value,\n\t\t\tuser: user,\n\t\t})\n\t}\n\treturn pairs\n}"} {"repo":"gin","file":"auth.go","line":91,"symbol":"authorizationHeader","kind":"function","lang":"go","code":"func authorizationHeader(user, password string) string {\n\tbase := user + \":\" + password\n\treturn \"Basic \" + base64.StdEncoding.EncodeToString(bytesconv.StringToBytes(base))\n}"} {"repo":"gin","file":"auth.go","line":98,"symbol":"BasicAuthForProxy","kind":"function","lang":"go","doc":"BasicAuthForProxy returns a Basic HTTP Proxy-Authorization middleware. If the realm is empty, \"Proxy Authorization Required\" will be used by default.","code":"func BasicAuthForProxy(accounts Accounts, realm string) HandlerFunc {\n\tif realm == \"\" {\n\t\trealm = \"Proxy Authorization Required\"\n\t}\n\trealm = \"Basic realm=\" + strconv.Quote(realm)\n\tpairs := processAccounts(accounts)\n\treturn func(c *Context) {\n\t\tproxyUser, found := pairs.searchCredential(c.requestHeader(\"Proxy-Authorization\"))\n\t\tif !found {\n\t\t\t// Credentials doesn't match, we return 407 and abort handlers chain.\n\t\t\tc.Header(\"Proxy-Authenticate\", realm)\n\t\t\tc.AbortWithStatus(http.StatusProxyAuthRequired)\n\t\t\treturn\n\t\t}\n\t\t// The proxy_user credentials was found, set proxy_user's id to key AuthProxyUserKey in this context, the proxy_user's id can be read later using\n\t\t// c.MustGet(gin.AuthProxyUserKey).\n\t\tc.Set(AuthProxyUserKey, proxyUser)\n\t}\n}"} {"repo":"gin","file":"auth_test.go","line":16,"symbol":"TestBasicAuth","kind":"function","lang":"go","code":"func TestBasicAuth(t *testing.T) {\n\tpairs := processAccounts(Accounts{\n\t\t\"admin\": \"password\",\n\t\t\"foo\": \"bar\",\n\t\t\"bar\": \"foo\",\n\t})\n\n\tassert.Len(t, pairs, 3)\n\tassert.Contains(t, pairs, authPair{\n\t\tuser: \"bar\",\n\t\tvalue: \"Basic YmFyOmZvbw==\",\n\t})\n\tassert.Contains(t, pairs, authPair{\n\t\tuser: \"foo\",\n\t\tvalue: \"Basic Zm9vOmJhcg==\",\n\t})\n\tassert.Contains(t, pairs, authPair{\n\t\tuser: \"admin\",\n\t\tvalue: \"Basic YWRtaW46cGFzc3dvcmQ=\",\n\t})\n}"} {"repo":"gin","file":"auth_test.go","line":38,"symbol":"TestBasicAuthFails","kind":"function","lang":"go","code":"func TestBasicAuthFails(t *testing.T) {\n\tassert.Panics(t, func() { processAccounts(nil) })\n\tassert.Panics(t, func() {\n\t\tprocessAccounts(Accounts{\n\t\t\t\"\": \"password\",\n\t\t\t\"foo\": \"bar\",\n\t\t})\n\t})\n}"} {"repo":"gin","file":"auth_test.go","line":48,"symbol":"TestBasicAuthSearchCredential","kind":"function","lang":"go","code":"func TestBasicAuthSearchCredential(t *testing.T) {\n\tpairs := processAccounts(Accounts{\n\t\t\"admin\": \"password\",\n\t\t\"foo\": \"bar\",\n\t\t\"bar\": \"foo\",\n\t})\n\n\tuser, found := pairs.searchCredential(authorizationHeader(\"admin\", \"password\"))\n\tassert.Equal(t, \"admin\", user)\n\tassert.True(t, found)\n\n\tuser, found = pairs.searchCredential(authorizationHeader(\"foo\", \"bar\"))\n\tassert.Equal(t, \"foo\", user)\n\tassert.True(t, found)\n\n\tuser, found = pairs.searchCredential(authorizationHeader(\"bar\", \"foo\"))\n\tassert.Equal(t, \"bar\", user)\n\tassert.True(t, found)\n\n\tuser, found = pairs.searchCredential(authorizationHeader(\"admins\", \"password\"))\n\tassert.Empty(t, user)\n\tassert.False(t, found)\n\n\tuser, found = pairs.searchCredential(authorizationHeader(\"foo\", \"bar \"))\n\tassert.Empty(t, user)\n\tassert.False(t, found)\n\n\tuser, found = pairs.searchCredential(\"\")\n\tassert.Empty(t, user)\n\tassert.False(t, found)\n}"} {"repo":"gin","file":"auth_test.go","line":80,"symbol":"TestBasicAuthAuthorizationHeader","kind":"function","lang":"go","code":"func TestBasicAuthAuthorizationHeader(t *testing.T) {\n\tassert.Equal(t, \"Basic YWRtaW46cGFzc3dvcmQ=\", authorizationHeader(\"admin\", \"password\"))\n}"} {"repo":"gin","file":"auth_test.go","line":84,"symbol":"TestBasicAuthSucceed","kind":"function","lang":"go","code":"func TestBasicAuthSucceed(t *testing.T) {\n\taccounts := Accounts{\"admin\": \"password\"}\n\trouter := New()\n\trouter.Use(BasicAuth(accounts))\n\trouter.GET(\"/login\", func(c *Context) {\n\t\tc.String(http.StatusOK, c.MustGet(AuthUserKey).(string))\n\t})\n\n\tw := httptest.NewRecorder()\n\treq, _ := http.NewRequest(http.MethodGet, \"/login\", nil)\n\treq.Header.Set(\"Authorization\", authorizationHeader(\"admin\", \"password\"))\n\trouter.ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"admin\", w.Body.String())\n}"} {"repo":"gin","file":"auth_test.go","line":101,"symbol":"TestBasicAuth401","kind":"function","lang":"go","code":"func TestBasicAuth401(t *testing.T) {\n\tcalled := false\n\taccounts := Accounts{\"foo\": \"bar\"}\n\trouter := New()\n\trouter.Use(BasicAuth(accounts))\n\trouter.GET(\"/login\", func(c *Context) {\n\t\tcalled = true\n\t\tc.String(http.StatusOK, c.MustGet(AuthUserKey).(string))\n\t})\n\n\tw := httptest.NewRecorder()\n\treq, _ := http.NewRequest(http.MethodGet, \"/login\", nil)\n\treq.Header.Set(\"Authorization\", \"Basic \"+base64.StdEncoding.EncodeToString([]byte(\"admin:password\")))\n\trouter.ServeHTTP(w, req)\n\n\tassert.False(t, called)\n\tassert.Equal(t, http.StatusUnauthorized, w.Code)\n\tassert.Equal(t, \"Basic realm=\\\"Authorization Required\\\"\", w.Header().Get(\"WWW-Authenticate\"))\n}"} {"repo":"gin","file":"auth_test.go","line":121,"symbol":"TestBasicAuth401WithCustomRealm","kind":"function","lang":"go","code":"func TestBasicAuth401WithCustomRealm(t *testing.T) {\n\tcalled := false\n\taccounts := Accounts{\"foo\": \"bar\"}\n\trouter := New()\n\trouter.Use(BasicAuthForRealm(accounts, \"My Custom \\\"Realm\\\"\"))\n\trouter.GET(\"/login\", func(c *Context) {\n\t\tcalled = true\n\t\tc.String(http.StatusOK, c.MustGet(AuthUserKey).(string))\n\t})\n\n\tw := httptest.NewRecorder()\n\treq, _ := http.NewRequest(http.MethodGet, \"/login\", nil)\n\treq.Header.Set(\"Authorization\", \"Basic \"+base64.StdEncoding.EncodeToString([]byte(\"admin:password\")))\n\trouter.ServeHTTP(w, req)\n\n\tassert.False(t, called)\n\tassert.Equal(t, http.StatusUnauthorized, w.Code)\n\tassert.Equal(t, \"Basic realm=\\\"My Custom \\\\\\\"Realm\\\\\\\"\\\"\", w.Header().Get(\"WWW-Authenticate\"))\n}"} {"repo":"gin","file":"auth_test.go","line":141,"symbol":"TestBasicAuthForProxySucceed","kind":"function","lang":"go","code":"func TestBasicAuthForProxySucceed(t *testing.T) {\n\taccounts := Accounts{\"admin\": \"password\"}\n\trouter := New()\n\trouter.Use(BasicAuthForProxy(accounts, \"\"))\n\trouter.Any(\"/*proxyPath\", func(c *Context) {\n\t\tc.String(http.StatusOK, c.MustGet(AuthProxyUserKey).(string))\n\t})\n\n\tw := httptest.NewRecorder()\n\treq, _ := http.NewRequest(http.MethodGet, \"/test\", nil)\n\treq.Header.Set(\"Proxy-Authorization\", authorizationHeader(\"admin\", \"password\"))\n\trouter.ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"admin\", w.Body.String())\n}"} {"repo":"gin","file":"auth_test.go","line":158,"symbol":"TestBasicAuthForProxy407","kind":"function","lang":"go","code":"func TestBasicAuthForProxy407(t *testing.T) {\n\tcalled := false\n\taccounts := Accounts{\"foo\": \"bar\"}\n\trouter := New()\n\trouter.Use(BasicAuthForProxy(accounts, \"\"))\n\trouter.Any(\"/*proxyPath\", func(c *Context) {\n\t\tcalled = true\n\t\tc.String(http.StatusOK, c.MustGet(AuthProxyUserKey).(string))\n\t})\n\n\tw := httptest.NewRecorder()\n\treq, _ := http.NewRequest(http.MethodGet, \"/test\", nil)\n\treq.Header.Set(\"Proxy-Authorization\", \"Basic \"+base64.StdEncoding.EncodeToString([]byte(\"admin:password\")))\n\trouter.ServeHTTP(w, req)\n\n\tassert.False(t, called)\n\tassert.Equal(t, http.StatusProxyAuthRequired, w.Code)\n\tassert.Equal(t, \"Basic realm=\\\"Proxy Authorization Required\\\"\", w.Header().Get(\"Proxy-Authenticate\"))\n}"} {"repo":"gin","file":"benchmarks_test.go","line":14,"symbol":"BenchmarkOneRoute","kind":"function","lang":"go","code":"func BenchmarkOneRoute(B *testing.B) {\n\trouter := New()\n\trouter.GET(\"/ping\", func(c *Context) {})\n\trunRequest(B, router, http.MethodGet, \"/ping\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":20,"symbol":"BenchmarkRecoveryMiddleware","kind":"function","lang":"go","code":"func BenchmarkRecoveryMiddleware(B *testing.B) {\n\trouter := New()\n\trouter.Use(Recovery())\n\trouter.GET(\"/\", func(c *Context) {})\n\trunRequest(B, router, http.MethodGet, \"/\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":27,"symbol":"BenchmarkLoggerMiddleware","kind":"function","lang":"go","code":"func BenchmarkLoggerMiddleware(B *testing.B) {\n\trouter := New()\n\trouter.Use(LoggerWithWriter(newMockWriter()))\n\trouter.GET(\"/\", func(c *Context) {})\n\trunRequest(B, router, http.MethodGet, \"/\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":34,"symbol":"BenchmarkManyHandlers","kind":"function","lang":"go","code":"func BenchmarkManyHandlers(B *testing.B) {\n\trouter := New()\n\trouter.Use(Recovery(), LoggerWithWriter(newMockWriter()))\n\trouter.Use(func(c *Context) {})\n\trouter.Use(func(c *Context) {})\n\trouter.GET(\"/ping\", func(c *Context) {})\n\trunRequest(B, router, http.MethodGet, \"/ping\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":43,"symbol":"Benchmark5Params","kind":"function","lang":"go","code":"func Benchmark5Params(B *testing.B) {\n\tDefaultWriter = os.Stdout\n\trouter := New()\n\trouter.Use(func(c *Context) {})\n\trouter.GET(\"/param/:param1/:params2/:param3/:param4/:param5\", func(c *Context) {})\n\trunRequest(B, router, http.MethodGet, \"/param/path/to/parameter/john/12345\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":51,"symbol":"BenchmarkOneRouteJSON","kind":"function","lang":"go","code":"func BenchmarkOneRouteJSON(B *testing.B) {\n\trouter := New()\n\tdata := struct {\n\t\tStatus string `json:\"status\"`\n\t}{\"ok\"}\n\trouter.GET(\"/json\", func(c *Context) {\n\t\tc.JSON(http.StatusOK, data)\n\t})\n\trunRequest(B, router, http.MethodGet, \"/json\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":62,"symbol":"BenchmarkOneRouteHTML","kind":"function","lang":"go","code":"func BenchmarkOneRouteHTML(B *testing.B) {\n\trouter := New()\n\tt := template.Must(template.New(\"index\").Parse(`\n\t\t

{{.}}

`))\n\trouter.SetHTMLTemplate(t)\n\n\trouter.GET(\"/html\", func(c *Context) {\n\t\tc.HTML(http.StatusOK, \"index\", \"hola\")\n\t})\n\trunRequest(B, router, http.MethodGet, \"/html\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":74,"symbol":"BenchmarkOneRouteSet","kind":"function","lang":"go","code":"func BenchmarkOneRouteSet(B *testing.B) {\n\trouter := New()\n\trouter.GET(\"/ping\", func(c *Context) {\n\t\tc.Set(\"key\", \"value\")\n\t})\n\trunRequest(B, router, http.MethodGet, \"/ping\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":82,"symbol":"BenchmarkOneRouteString","kind":"function","lang":"go","code":"func BenchmarkOneRouteString(B *testing.B) {\n\trouter := New()\n\trouter.GET(\"/text\", func(c *Context) {\n\t\tc.String(http.StatusOK, \"this is a plain text\")\n\t})\n\trunRequest(B, router, http.MethodGet, \"/text\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":90,"symbol":"BenchmarkManyRoutesFirst","kind":"function","lang":"go","code":"func BenchmarkManyRoutesFirst(B *testing.B) {\n\trouter := New()\n\trouter.Any(\"/ping\", func(c *Context) {})\n\trunRequest(B, router, http.MethodGet, \"/ping\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":96,"symbol":"BenchmarkManyRoutesLast","kind":"function","lang":"go","code":"func BenchmarkManyRoutesLast(B *testing.B) {\n\trouter := New()\n\trouter.Any(\"/ping\", func(c *Context) {})\n\trunRequest(B, router, \"OPTIONS\", \"/ping\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":102,"symbol":"Benchmark404","kind":"function","lang":"go","code":"func Benchmark404(B *testing.B) {\n\trouter := New()\n\trouter.Any(\"/something\", func(c *Context) {})\n\trouter.NoRoute(func(c *Context) {})\n\trunRequest(B, router, http.MethodGet, \"/ping\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":109,"symbol":"Benchmark404Many","kind":"function","lang":"go","code":"func Benchmark404Many(B *testing.B) {\n\trouter := New()\n\trouter.GET(\"/\", func(c *Context) {})\n\trouter.GET(\"/path/to/something\", func(c *Context) {})\n\trouter.GET(\"/post/:id\", func(c *Context) {})\n\trouter.GET(\"/view/:id\", func(c *Context) {})\n\trouter.GET(\"/favicon.ico\", func(c *Context) {})\n\trouter.GET(\"/robots.txt\", func(c *Context) {})\n\trouter.GET(\"/delete/:id\", func(c *Context) {})\n\trouter.GET(\"/user/:id/:mode\", func(c *Context) {})\n\n\trouter.NoRoute(func(c *Context) {})\n\trunRequest(B, router, http.MethodGet, \"/viewfake\")\n}"} {"repo":"gin","file":"benchmarks_test.go","line":124,"symbol":"mockWriter","kind":"type","lang":"go","code":"type mockWriter struct {\n\theaders http.Header\n}"} {"repo":"gin","file":"benchmarks_test.go","line":128,"symbol":"newMockWriter","kind":"function","lang":"go","code":"func newMockWriter() *mockWriter {\n\treturn &mockWriter{\n\t\thttp.Header{},\n\t}\n}"} {"repo":"gin","file":"benchmarks_test.go","line":134,"symbol":"Header","kind":"method","lang":"go","code":"func (m *mockWriter) Header() (h http.Header) {\n\treturn m.headers\n}"} {"repo":"gin","file":"benchmarks_test.go","line":138,"symbol":"Write","kind":"method","lang":"go","code":"func (m *mockWriter) Write(p []byte) (n int, err error) {\n\treturn len(p), nil\n}"} {"repo":"gin","file":"benchmarks_test.go","line":142,"symbol":"WriteString","kind":"method","lang":"go","code":"func (m *mockWriter) WriteString(s string) (n int, err error) {\n\treturn len(s), nil\n}"} {"repo":"gin","file":"benchmarks_test.go","line":146,"symbol":"WriteHeader","kind":"method","lang":"go","code":"func (m *mockWriter) WriteHeader(int) {}"} {"repo":"gin","file":"benchmarks_test.go","line":148,"symbol":"runRequest","kind":"function","lang":"go","code":"func runRequest(B *testing.B, r *Engine, method, path string) {\n\t// create fake request\n\treq, err := http.NewRequest(method, path, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tw := newMockWriter()\n\tB.ReportAllocs()\n\tB.ResetTimer()\n\tfor B.Loop() {\n\t\tr.ServeHTTP(w, req)\n\t}\n}"} {"repo":"gin","file":"binding/binding.go","line":13,"symbol":"MIMEJSON","kind":"constant","lang":"go","code":"MIMEJSON = \"application/json\""} {"repo":"gin","file":"binding/binding.go","line":14,"symbol":"MIMEHTML","kind":"constant","lang":"go","code":"MIMEHTML = \"text/html\""} {"repo":"gin","file":"binding/binding.go","line":15,"symbol":"MIMEXML","kind":"constant","lang":"go","code":"MIMEXML = \"application/xml\""} {"repo":"gin","file":"binding/binding.go","line":16,"symbol":"MIMEXML2","kind":"constant","lang":"go","code":"MIMEXML2 = \"text/xml\""} {"repo":"gin","file":"binding/binding.go","line":17,"symbol":"MIMEPlain","kind":"constant","lang":"go","code":"MIMEPlain = \"text/plain\""} {"repo":"gin","file":"binding/binding.go","line":18,"symbol":"MIMEPOSTForm","kind":"constant","lang":"go","code":"MIMEPOSTForm = \"application/x-www-form-urlencoded\""} {"repo":"gin","file":"binding/binding.go","line":19,"symbol":"MIMEMultipartPOSTForm","kind":"constant","lang":"go","code":"MIMEMultipartPOSTForm = \"multipart/form-data\""} {"repo":"gin","file":"binding/binding.go","line":20,"symbol":"MIMEPROTOBUF","kind":"constant","lang":"go","code":"MIMEPROTOBUF = \"application/x-protobuf\""} {"repo":"gin","file":"binding/binding.go","line":21,"symbol":"MIMEMSGPACK","kind":"constant","lang":"go","code":"MIMEMSGPACK = \"application/x-msgpack\""} {"repo":"gin","file":"binding/binding.go","line":22,"symbol":"MIMEMSGPACK2","kind":"constant","lang":"go","code":"MIMEMSGPACK2 = \"application/msgpack\""} {"repo":"gin","file":"binding/binding.go","line":23,"symbol":"MIMEYAML","kind":"constant","lang":"go","code":"MIMEYAML = \"application/x-yaml\""} {"repo":"gin","file":"binding/binding.go","line":24,"symbol":"MIMEYAML2","kind":"constant","lang":"go","code":"MIMEYAML2 = \"application/yaml\""} {"repo":"gin","file":"binding/binding.go","line":25,"symbol":"MIMETOML","kind":"constant","lang":"go","code":"MIMETOML = \"application/toml\""} {"repo":"gin","file":"binding/binding.go","line":26,"symbol":"MIMEBSON","kind":"constant","lang":"go","code":"MIMEBSON = \"application/bson\""} {"repo":"gin","file":"binding/binding.go","line":32,"symbol":"Binding","kind":"type","lang":"go","doc":"Binding describes the interface which needs to be implemented for binding the data present in the request such as JSON request body, query parameters or the form POST.","code":"type Binding interface {\n\tName() string\n\tBind(*http.Request, any) error\n}"} {"repo":"gin","file":"binding/binding.go","line":39,"symbol":"BindingBody","kind":"type","lang":"go","doc":"BindingBody adds BindBody method to Binding. BindBody is similar with Bind, but it reads the body from supplied bytes instead of req.Body.","code":"type BindingBody interface {\n\tBinding\n\tBindBody([]byte, any) error\n}"} {"repo":"gin","file":"binding/binding.go","line":46,"symbol":"BindingUri","kind":"type","lang":"go","doc":"BindingUri adds BindUri method to Binding. BindUri is similar with Bind, but it reads the Params.","code":"type BindingUri interface {\n\tName() string\n\tBindUri(map[string][]string, any) error\n}"} {"repo":"gin","file":"binding/binding.go","line":55,"symbol":"StructValidator","kind":"type","lang":"go","doc":"StructValidator is the minimal interface which needs to be implemented in order for it to be used as the validator engine for ensuring the correctness of the request. Gin provides a default implementation for this using https://github.com/go-playground/validator/tree/v10.6.1.","code":"type StructValidator interface {\n\t// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.\n\t// If the received type is a slice|array, the validation should be performed travel on every element.\n\t// If the received type is not a struct or slice|array, any validation should be skipped and nil must be returned.\n\t// If the received type is a struct or pointer to a struct, the validation should be performed.\n\t// If the struct is not valid or the validation itself fails, a descriptive error should be returned.\n\t// Otherwise nil must be returned.\n\tValidateStruct(any) error\n\n\t// Engine returns the underlying validator engine which powers the\n\t// StructValidator implementation.\n\tEngine() any\n}"} {"repo":"gin","file":"binding/binding.go","line":72,"symbol":"Validator","kind":"variable","lang":"go","doc":"Validator is the default validator which implements the StructValidator interface. It uses https://github.com/go-playground/validator/tree/v10.6.1 under the hood.","code":"Validator StructValidator = &defaultValidator{}"} {"repo":"gin","file":"binding/binding.go","line":77,"symbol":"JSON","kind":"variable","lang":"go","code":"JSON BindingBody = jsonBinding{}"} {"repo":"gin","file":"binding/binding.go","line":78,"symbol":"XML","kind":"variable","lang":"go","code":"XML BindingBody = xmlBinding{}"} {"repo":"gin","file":"binding/binding.go","line":79,"symbol":"Form","kind":"variable","lang":"go","code":"Form Binding = formBinding{}"} {"repo":"gin","file":"binding/binding.go","line":80,"symbol":"Query","kind":"variable","lang":"go","code":"Query Binding = queryBinding{}"} {"repo":"gin","file":"binding/binding.go","line":81,"symbol":"FormPost","kind":"variable","lang":"go","code":"FormPost Binding = formPostBinding{}"} {"repo":"gin","file":"binding/binding.go","line":82,"symbol":"FormMultipart","kind":"variable","lang":"go","code":"FormMultipart Binding = formMultipartBinding{}"} {"repo":"gin","file":"binding/binding.go","line":83,"symbol":"ProtoBuf","kind":"variable","lang":"go","code":"ProtoBuf BindingBody = protobufBinding{}"} {"repo":"gin","file":"binding/binding.go","line":84,"symbol":"MsgPack","kind":"variable","lang":"go","code":"MsgPack BindingBody = msgpackBinding{}"} {"repo":"gin","file":"binding/binding.go","line":85,"symbol":"YAML","kind":"variable","lang":"go","code":"YAML BindingBody = yamlBinding{}"} {"repo":"gin","file":"binding/binding.go","line":86,"symbol":"Uri","kind":"variable","lang":"go","code":"Uri BindingUri = uriBinding{}"} {"repo":"gin","file":"binding/binding.go","line":87,"symbol":"Header","kind":"variable","lang":"go","code":"Header Binding = headerBinding{}"} {"repo":"gin","file":"binding/binding.go","line":88,"symbol":"Plain","kind":"variable","lang":"go","code":"Plain BindingBody = plainBinding{}"} {"repo":"gin","file":"binding/binding.go","line":89,"symbol":"TOML","kind":"variable","lang":"go","code":"TOML BindingBody = tomlBinding{}"} {"repo":"gin","file":"binding/binding.go","line":90,"symbol":"BSON","kind":"variable","lang":"go","code":"BSON BindingBody = bsonBinding{}"} {"repo":"gin","file":"binding/binding.go","line":95,"symbol":"Default","kind":"function","lang":"go","doc":"Default returns the appropriate Binding instance based on the HTTP method and the content type.","code":"func Default(method, contentType string) Binding {\n\tif method == http.MethodGet {\n\t\treturn Form\n\t}\n\n\tswitch contentType {\n\tcase MIMEJSON:\n\t\treturn JSON\n\tcase MIMEXML, MIMEXML2:\n\t\treturn XML\n\tcase MIMEPROTOBUF:\n\t\treturn ProtoBuf\n\tcase MIMEMSGPACK, MIMEMSGPACK2:\n\t\treturn MsgPack\n\tcase MIMEYAML, MIMEYAML2:\n\t\treturn YAML\n\tcase MIMETOML:\n\t\treturn TOML\n\tcase MIMEMultipartPOSTForm:\n\t\treturn FormMultipart\n\tcase MIMEBSON:\n\t\treturn BSON\n\tdefault: // case MIMEPOSTForm:\n\t\treturn Form\n\t}\n}"} {"repo":"gin","file":"binding/binding.go","line":122,"symbol":"validate","kind":"function","lang":"go","code":"func validate(obj any) error {\n\tif Validator == nil {\n\t\treturn nil\n\t}\n\treturn Validator.ValidateStruct(obj)\n}"} {"repo":"gin","file":"binding/binding_msgpack_test.go","line":19,"symbol":"TestBindingMsgPack","kind":"function","lang":"go","code":"func TestBindingMsgPack(t *testing.T) {\n\ttest := FooStruct{\n\t\tFoo: \"bar\",\n\t}\n\n\th := new(codec.MsgpackHandle)\n\tassert.NotNil(t, h)\n\tbuf := bytes.NewBuffer([]byte{})\n\tassert.NotNil(t, buf)\n\terr := codec.NewEncoder(buf, h).Encode(test)\n\trequire.NoError(t, err)\n\n\tdata := buf.Bytes()\n\n\ttestMsgPackBodyBinding(t,\n\t\tMsgPack, \"msgpack\",\n\t\t\"/\", \"/\",\n\t\tstring(data), string(data[1:]))\n}"} {"repo":"gin","file":"binding/binding_msgpack_test.go","line":39,"symbol":"testMsgPackBodyBinding","kind":"function","lang":"go","code":"func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {\n\tassert.Equal(t, name, b.Name())\n\n\tobj := FooStruct{}\n\treq := requestWithBody(http.MethodPost, path, body)\n\treq.Header.Add(\"Content-Type\", MIMEMSGPACK)\n\terr := b.Bind(req, &obj)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"bar\", obj.Foo)\n\n\tobj = FooStruct{}\n\treq = requestWithBody(http.MethodPost, badPath, badBody)\n\treq.Header.Add(\"Content-Type\", MIMEMSGPACK)\n\terr = MsgPack.Bind(req, &obj)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"binding/binding_msgpack_test.go","line":56,"symbol":"TestBindingDefaultMsgPack","kind":"function","lang":"go","code":"func TestBindingDefaultMsgPack(t *testing.T) {\n\tassert.Equal(t, MsgPack, Default(http.MethodPost, MIMEMSGPACK))\n\tassert.Equal(t, MsgPack, Default(http.MethodPut, MIMEMSGPACK2))\n}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":13,"symbol":"MIMEJSON","kind":"constant","lang":"go","code":"MIMEJSON = \"application/json\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":14,"symbol":"MIMEHTML","kind":"constant","lang":"go","code":"MIMEHTML = \"text/html\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":15,"symbol":"MIMEXML","kind":"constant","lang":"go","code":"MIMEXML = \"application/xml\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":16,"symbol":"MIMEXML2","kind":"constant","lang":"go","code":"MIMEXML2 = \"text/xml\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":17,"symbol":"MIMEPlain","kind":"constant","lang":"go","code":"MIMEPlain = \"text/plain\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":18,"symbol":"MIMEPOSTForm","kind":"constant","lang":"go","code":"MIMEPOSTForm = \"application/x-www-form-urlencoded\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":19,"symbol":"MIMEMultipartPOSTForm","kind":"constant","lang":"go","code":"MIMEMultipartPOSTForm = \"multipart/form-data\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":20,"symbol":"MIMEPROTOBUF","kind":"constant","lang":"go","code":"MIMEPROTOBUF = \"application/x-protobuf\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":21,"symbol":"MIMEYAML","kind":"constant","lang":"go","code":"MIMEYAML = \"application/x-yaml\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":22,"symbol":"MIMEYAML2","kind":"constant","lang":"go","code":"MIMEYAML2 = \"application/yaml\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":23,"symbol":"MIMETOML","kind":"constant","lang":"go","code":"MIMETOML = \"application/toml\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":24,"symbol":"MIMEBSON","kind":"constant","lang":"go","code":"MIMEBSON = \"application/bson\""} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":30,"symbol":"Binding","kind":"type","lang":"go","doc":"Binding describes the interface which needs to be implemented for binding the data present in the request such as JSON request body, query parameters or the form POST.","code":"type Binding interface {\n\tName() string\n\tBind(*http.Request, any) error\n}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":37,"symbol":"BindingBody","kind":"type","lang":"go","doc":"BindingBody adds BindBody method to Binding. BindBody is similar with Bind, but it reads the body from supplied bytes instead of req.Body.","code":"type BindingBody interface {\n\tBinding\n\tBindBody([]byte, any) error\n}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":44,"symbol":"BindingUri","kind":"type","lang":"go","doc":"BindingUri adds BindUri method to Binding. BindUri is similar with Bind, but it reads the Params.","code":"type BindingUri interface {\n\tName() string\n\tBindUri(map[string][]string, any) error\n}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":53,"symbol":"StructValidator","kind":"type","lang":"go","doc":"StructValidator is the minimal interface which needs to be implemented in order for it to be used as the validator engine for ensuring the correctness of the request. Gin provides a default implementation for this using https://github.com/go-playground/validator/tree/v10.6.1.","code":"type StructValidator interface {\n\t// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.\n\t// If the received type is not a struct, any validation should be skipped and nil must be returned.\n\t// If the received type is a struct or pointer to a struct, the validation should be performed.\n\t// If the struct is not valid or the validation itself fails, a descriptive error should be returned.\n\t// Otherwise nil must be returned.\n\tValidateStruct(any) error\n\n\t// Engine returns the underlying validator engine which powers the\n\t// StructValidator implementation.\n\tEngine() any\n}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":69,"symbol":"Validator","kind":"variable","lang":"go","doc":"Validator is the default validator which implements the StructValidator interface. It uses https://github.com/go-playground/validator/tree/v10.6.1 under the hood.","code":"Validator StructValidator = &defaultValidator{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":74,"symbol":"JSON","kind":"variable","lang":"go","code":"JSON = jsonBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":75,"symbol":"XML","kind":"variable","lang":"go","code":"XML = xmlBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":76,"symbol":"Form","kind":"variable","lang":"go","code":"Form = formBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":77,"symbol":"Query","kind":"variable","lang":"go","code":"Query = queryBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":78,"symbol":"FormPost","kind":"variable","lang":"go","code":"FormPost = formPostBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":79,"symbol":"FormMultipart","kind":"variable","lang":"go","code":"FormMultipart = formMultipartBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":80,"symbol":"ProtoBuf","kind":"variable","lang":"go","code":"ProtoBuf = protobufBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":81,"symbol":"YAML","kind":"variable","lang":"go","code":"YAML = yamlBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":82,"symbol":"Uri","kind":"variable","lang":"go","code":"Uri = uriBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":83,"symbol":"Header","kind":"variable","lang":"go","code":"Header = headerBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":84,"symbol":"TOML","kind":"variable","lang":"go","code":"TOML = tomlBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":85,"symbol":"Plain","kind":"variable","lang":"go","code":"Plain = plainBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":86,"symbol":"BSON","kind":"variable","lang":"go","code":"BSON BindingBody = bsonBinding{}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":91,"symbol":"Default","kind":"function","lang":"go","doc":"Default returns the appropriate Binding instance based on the HTTP method and the content type.","code":"func Default(method, contentType string) Binding {\n\tif method == \"GET\" {\n\t\treturn Form\n\t}\n\n\tswitch contentType {\n\tcase MIMEJSON:\n\t\treturn JSON\n\tcase MIMEXML, MIMEXML2:\n\t\treturn XML\n\tcase MIMEPROTOBUF:\n\t\treturn ProtoBuf\n\tcase MIMEYAML, MIMEYAML2:\n\t\treturn YAML\n\tcase MIMEMultipartPOSTForm:\n\t\treturn FormMultipart\n\tcase MIMETOML:\n\t\treturn TOML\n\tcase MIMEBSON:\n\t\treturn BSON\n\tdefault: // case MIMEPOSTForm:\n\t\treturn Form\n\t}\n}"} {"repo":"gin","file":"binding/binding_nomsgpack.go","line":116,"symbol":"validate","kind":"function","lang":"go","code":"func validate(obj any) error {\n\tif Validator == nil {\n\t\treturn nil\n\t}\n\treturn Validator.ValidateStruct(obj)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":28,"symbol":"appkey","kind":"type","lang":"go","code":"type appkey struct {\n\tAppkey string `json:\"appkey\" form:\"appkey\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":32,"symbol":"QueryTest","kind":"type","lang":"go","code":"type QueryTest struct {\n\tPage int `json:\"page\" form:\"page\"`\n\tSize int `json:\"size\" form:\"size\"`\n\tappkey\n}"} {"repo":"gin","file":"binding/binding_test.go","line":38,"symbol":"FooStruct","kind":"type","lang":"go","code":"type FooStruct struct {\n\tFoo string `msgpack:\"foo\" json:\"foo\" form:\"foo\" xml:\"foo\" binding:\"required,max=32\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":42,"symbol":"FooBarStruct","kind":"type","lang":"go","code":"type FooBarStruct struct {\n\tFooStruct\n\tBar string `msgpack:\"bar\" json:\"bar\" form:\"bar\" xml:\"bar\" binding:\"required\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":47,"symbol":"FooBarFileStruct","kind":"type","lang":"go","code":"type FooBarFileStruct struct {\n\tFooBarStruct\n\tFile *multipart.FileHeader `form:\"file\" binding:\"required\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":52,"symbol":"FooBarFileFailStruct","kind":"type","lang":"go","code":"type FooBarFileFailStruct struct {\n\tFooBarStruct\n\tFile *multipart.FileHeader `invalid_name:\"file\" binding:\"required\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":57,"symbol":"FooDefaultBarStruct","kind":"type","lang":"go","code":"type FooDefaultBarStruct struct {\n\tFooStruct\n\tBar string `msgpack:\"bar\" json:\"bar\" form:\"bar,default=hello\" xml:\"bar\" binding:\"required\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":62,"symbol":"FooStructUseNumber","kind":"type","lang":"go","code":"type FooStructUseNumber struct {\n\tFoo any `json:\"foo\" binding:\"required\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":66,"symbol":"FooStructDisallowUnknownFields","kind":"type","lang":"go","code":"type FooStructDisallowUnknownFields struct {\n\tFoo any `json:\"foo\" binding:\"required\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":70,"symbol":"FooBarStructForTimeType","kind":"type","lang":"go","code":"type FooBarStructForTimeType struct {\n\tTimeFoo time.Time `form:\"time_foo\" time_format:\"2006-01-02\" time_utc:\"1\" time_location:\"Asia/Chongqing\"`\n\tTimeBar time.Time `form:\"time_bar\" time_format:\"2006-01-02\" time_utc:\"1\"`\n\tCreateTime time.Time `form:\"createTime\" time_format:\"unixNano\"`\n\tUnixTime time.Time `form:\"unixTime\" time_format:\"unix\"`\n\tUnixMilliTime time.Time `form:\"unixMilliTime\" time_format:\"unixmilli\"`\n\tUnixMicroTime time.Time `form:\"unixMicroTime\" time_format:\"uNiXmiCrO\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":79,"symbol":"FooStructForTimeTypeNotUnixFormat","kind":"type","lang":"go","code":"type FooStructForTimeTypeNotUnixFormat struct {\n\tCreateTime time.Time `form:\"createTime\" time_format:\"unixNano\"`\n\tUnixTime time.Time `form:\"unixTime\" time_format:\"unix\"`\n\tUnixMilliTime time.Time `form:\"unixMilliTime\" time_format:\"unixMilli\"`\n\tUnixMicroTime time.Time `form:\"unixMicroTime\" time_format:\"unixMicro\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":86,"symbol":"FooStructForTimeTypeNotFormat","kind":"type","lang":"go","code":"type FooStructForTimeTypeNotFormat struct {\n\tTimeFoo time.Time `form:\"time_foo\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":90,"symbol":"FooStructForTimeTypeFailFormat","kind":"type","lang":"go","code":"type FooStructForTimeTypeFailFormat struct {\n\tTimeFoo time.Time `form:\"time_foo\" time_format:\"2017-11-15\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":94,"symbol":"FooStructForTimeTypeFailLocation","kind":"type","lang":"go","code":"type FooStructForTimeTypeFailLocation struct {\n\tTimeFoo time.Time `form:\"time_foo\" time_format:\"2006-01-02\" time_location:\"/asia/chongqing\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":98,"symbol":"FooStructForMapType","kind":"type","lang":"go","code":"type FooStructForMapType struct {\n\tMapFoo map[string]any `form:\"map_foo\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":102,"symbol":"FooStructForIgnoreFormTag","kind":"type","lang":"go","code":"type FooStructForIgnoreFormTag struct {\n\tFoo *string `form:\"-\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":106,"symbol":"InvalidNameType","kind":"type","lang":"go","code":"type InvalidNameType struct {\n\tTestName string `invalid_name:\"test_name\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":110,"symbol":"InvalidNameMapType","kind":"type","lang":"go","code":"type InvalidNameMapType struct {\n\tTestName struct {\n\t\tMapFoo map[string]any `form:\"map_foo\"`\n\t}\n}"} {"repo":"gin","file":"binding/binding_test.go","line":116,"symbol":"FooStructForSliceType","kind":"type","lang":"go","code":"type FooStructForSliceType struct {\n\tSliceFoo []int `form:\"slice_foo\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":120,"symbol":"FooStructForStructType","kind":"type","lang":"go","code":"type FooStructForStructType struct {\n\tStructFoo struct {\n\t\tIdx int `form:\"idx\"`\n\t}\n}"} {"repo":"gin","file":"binding/binding_test.go","line":126,"symbol":"FooStructForStructPointerType","kind":"type","lang":"go","code":"type FooStructForStructPointerType struct {\n\tStructPointerFoo *struct {\n\t\tName string `form:\"name\"`\n\t}\n}"} {"repo":"gin","file":"binding/binding_test.go","line":132,"symbol":"FooStructForSliceMapType","kind":"type","lang":"go","code":"type FooStructForSliceMapType struct {\n\t// Unknown type: not support map\n\tSliceMapFoo []map[string]any `form:\"slice_map_foo\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":137,"symbol":"FooStructForBoolType","kind":"type","lang":"go","code":"type FooStructForBoolType struct {\n\tBoolFoo bool `form:\"bool_foo\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":141,"symbol":"FooStructForStringPtrType","kind":"type","lang":"go","code":"type FooStructForStringPtrType struct {\n\tPtrFoo *string `form:\"ptr_foo\"`\n\tPtrBar *string `form:\"ptr_bar\" binding:\"required\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":146,"symbol":"FooStructForMapPtrType","kind":"type","lang":"go","code":"type FooStructForMapPtrType struct {\n\tPtrBar *map[string]any `form:\"ptr_bar\"`\n}"} {"repo":"gin","file":"binding/binding_test.go","line":150,"symbol":"TestBindingDefault","kind":"function","lang":"go","code":"func TestBindingDefault(t *testing.T) {\n\tassert.Equal(t, Form, Default(http.MethodGet, \"\"))\n\tassert.Equal(t, Form, Default(http.MethodGet, MIMEJSON))\n\n\tassert.Equal(t, JSON, Default(http.MethodPost, MIMEJSON))\n\tassert.Equal(t, JSON, Default(http.MethodPut, MIMEJSON))\n\n\tassert.Equal(t, XML, Default(http.MethodPost, MIMEXML))\n\tassert.Equal(t, XML, Default(http.MethodPut, MIMEXML2))\n\n\tassert.Equal(t, Form, Default(http.MethodPost, MIMEPOSTForm))\n\tassert.Equal(t, Form, Default(http.MethodPut, MIMEPOSTForm))\n\n\tassert.Equal(t, FormMultipart, Default(http.MethodPost, MIMEMultipartPOSTForm))\n\tassert.Equal(t, FormMultipart, Default(http.MethodPut, MIMEMultipartPOSTForm))\n\n\tassert.Equal(t, ProtoBuf, Default(http.MethodPost, MIMEPROTOBUF))\n\tassert.Equal(t, ProtoBuf, Default(http.MethodPut, MIMEPROTOBUF))\n\n\tassert.Equal(t, YAML, Default(http.MethodPost, MIMEYAML))\n\tassert.Equal(t, YAML, Default(http.MethodPut, MIMEYAML))\n\tassert.Equal(t, YAML, Default(http.MethodPost, MIMEYAML2))\n\tassert.Equal(t, YAML, Default(http.MethodPut, MIMEYAML2))\n\n\tassert.Equal(t, TOML, Default(http.MethodPost, MIMETOML))\n\tassert.Equal(t, TOML, Default(http.MethodPut, MIMETOML))\n\n\tassert.Equal(t, BSON, Default(http.Met"} {"repo":"gin","file":"binding/binding_test.go","line":181,"symbol":"TestBindingJSONNilBody","kind":"function","lang":"go","code":"func TestBindingJSONNilBody(t *testing.T) {\n\tvar obj FooStruct\n\treq, _ := http.NewRequest(http.MethodPost, \"/\", nil)\n\terr := JSON.Bind(req, &obj)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":182,"symbol":"obj","kind":"variable","lang":"go","code":"obj FooStruct"} {"repo":"gin","file":"binding/binding_test.go","line":188,"symbol":"TestBindingJSON","kind":"function","lang":"go","code":"func TestBindingJSON(t *testing.T) {\n\ttestBodyBinding(t,\n\t\tJSON, \"json\",\n\t\t\"/\", \"/\",\n\t\t`{\"foo\": \"bar\"}`, `{\"bar\": \"foo\"}`)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":195,"symbol":"TestBindingJSONSlice","kind":"function","lang":"go","code":"func TestBindingJSONSlice(t *testing.T) {\n\tEnableDecoderDisallowUnknownFields = true\n\tdefer func() {\n\t\tEnableDecoderDisallowUnknownFields = false\n\t}()\n\n\ttestBodyBindingSlice(t, JSON, \"json\", \"/\", \"/\", `[]`, ``)\n\ttestBodyBindingSlice(t, JSON, \"json\", \"/\", \"/\", `[{\"foo\": \"123\"}]`, `[{}]`)\n\ttestBodyBindingSlice(t, JSON, \"json\", \"/\", \"/\", `[{\"foo\": \"123\"}]`, `[{\"foo\": \"\"}]`)\n\ttestBodyBindingSlice(t, JSON, \"json\", \"/\", \"/\", `[{\"foo\": \"123\"}]`, `[{\"foo\": 123}]`)\n\ttestBodyBindingSlice(t, JSON, \"json\", \"/\", \"/\", `[{\"foo\": \"123\"}]`, `[{\"bar\": 123}]`)\n\ttestBodyBindingSlice(t, JSON, \"json\", \"/\", \"/\", `[{\"foo\": \"123\"}]`, `[{\"foo\": \"123456789012345678901234567890123\"}]`)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":209,"symbol":"TestBindingJSONUseNumber","kind":"function","lang":"go","code":"func TestBindingJSONUseNumber(t *testing.T) {\n\ttestBodyBindingUseNumber(t,\n\t\tJSON, \"json\",\n\t\t\"/\", \"/\",\n\t\t`{\"foo\": 123}`, `{\"bar\": \"foo\"}`)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":216,"symbol":"TestBindingJSONUseNumber2","kind":"function","lang":"go","code":"func TestBindingJSONUseNumber2(t *testing.T) {\n\ttestBodyBindingUseNumber2(t,\n\t\tJSON, \"json\",\n\t\t\"/\", \"/\",\n\t\t`{\"foo\": 123}`, `{\"bar\": \"foo\"}`)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":223,"symbol":"TestBindingJSONDisallowUnknownFields","kind":"function","lang":"go","code":"func TestBindingJSONDisallowUnknownFields(t *testing.T) {\n\ttestBodyBindingDisallowUnknownFields(t, JSON,\n\t\t\"/\", \"/\",\n\t\t`{\"foo\": \"bar\"}`, `{\"foo\": \"bar\", \"what\": \"this\"}`)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":229,"symbol":"TestBindingJSONStringMap","kind":"function","lang":"go","code":"func TestBindingJSONStringMap(t *testing.T) {\n\ttestBodyBindingStringMap(t, JSON,\n\t\t\"/\", \"/\",\n\t\t`{\"foo\": \"bar\", \"hello\": \"world\"}`, `{\"num\": 2}`)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":235,"symbol":"TestBindingForm","kind":"function","lang":"go","code":"func TestBindingForm(t *testing.T) {\n\ttestFormBinding(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"foo=bar&bar=foo\", \"bar2=foo\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":241,"symbol":"TestBindingForm2","kind":"function","lang":"go","code":"func TestBindingForm2(t *testing.T) {\n\ttestFormBinding(t, http.MethodGet,\n\t\t\"/?foo=bar&bar=foo\", \"/?bar2=foo\",\n\t\t\"\", \"\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":247,"symbol":"TestBindingFormEmbeddedStruct","kind":"function","lang":"go","code":"func TestBindingFormEmbeddedStruct(t *testing.T) {\n\ttestFormBindingEmbeddedStruct(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"page=1&size=2&appkey=test-appkey\", \"bar2=foo\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":253,"symbol":"TestBindingFormEmbeddedStruct2","kind":"function","lang":"go","code":"func TestBindingFormEmbeddedStruct2(t *testing.T) {\n\ttestFormBindingEmbeddedStruct(t, http.MethodGet,\n\t\t\"/?page=1&size=2&appkey=test-appkey\", \"/?bar2=foo\",\n\t\t\"\", \"\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":259,"symbol":"TestBindingFormDefaultValue","kind":"function","lang":"go","code":"func TestBindingFormDefaultValue(t *testing.T) {\n\ttestFormBindingDefaultValue(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"foo=bar\", \"bar2=foo\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":265,"symbol":"TestBindingFormDefaultValue2","kind":"function","lang":"go","code":"func TestBindingFormDefaultValue2(t *testing.T) {\n\ttestFormBindingDefaultValue(t, http.MethodGet,\n\t\t\"/?foo=bar\", \"/?bar2=foo\",\n\t\t\"\", \"\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":271,"symbol":"TestBindingFormForTime","kind":"function","lang":"go","code":"func TestBindingFormForTime(t *testing.T) {\n\ttestFormBindingForTime(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"time_foo=2017-11-15&time_bar=&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012\", \"bar2=foo\")\n\ttestFormBindingForTimeNotUnixFormat(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"time_foo=2017-11-15&createTime=bad&unixTime=bad&unixMilliTime=bad&unixMicroTime=bad\", \"bar2=foo\")\n\ttestFormBindingForTimeNotFormat(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"time_foo=2017-11-15\", \"bar2=foo\")\n\ttestFormBindingForTimeFailFormat(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"time_foo=2017-11-15\", \"bar2=foo\")\n\ttestFormBindingForTimeFailLocation(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"time_foo=2017-11-15\", \"bar2=foo\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":289,"symbol":"TestBindingFormForTime2","kind":"function","lang":"go","code":"func TestBindingFormForTime2(t *testing.T) {\n\ttestFormBindingForTime(t, http.MethodGet,\n\t\t\"/?time_foo=2017-11-15&time_bar=&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012\", \"/?bar2=foo\",\n\t\t\"\", \"\")\n\ttestFormBindingForTimeNotUnixFormat(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"time_foo=2017-11-15&createTime=bad&unixTime=bad&unixMilliTime=bad&unixMicroTime=bad\", \"bar2=foo\")\n\ttestFormBindingForTimeNotFormat(t, http.MethodGet,\n\t\t\"/?time_foo=2017-11-15\", \"/?bar2=foo\",\n\t\t\"\", \"\")\n\ttestFormBindingForTimeFailFormat(t, http.MethodGet,\n\t\t\"/?time_foo=2017-11-15\", \"/?bar2=foo\",\n\t\t\"\", \"\")\n\ttestFormBindingForTimeFailLocation(t, http.MethodGet,\n\t\t\"/?time_foo=2017-11-15\", \"/?bar2=foo\",\n\t\t\"\", \"\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":307,"symbol":"TestFormBindingIgnoreField","kind":"function","lang":"go","code":"func TestFormBindingIgnoreField(t *testing.T) {\n\ttestFormBindingIgnoreField(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"-=bar\", \"\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":313,"symbol":"TestBindingFormInvalidName","kind":"function","lang":"go","code":"func TestBindingFormInvalidName(t *testing.T) {\n\ttestFormBindingInvalidName(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"test_name=bar\", \"bar2=foo\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":319,"symbol":"TestBindingFormInvalidName2","kind":"function","lang":"go","code":"func TestBindingFormInvalidName2(t *testing.T) {\n\ttestFormBindingInvalidName2(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"map_foo=bar\", \"bar2=foo\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":325,"symbol":"TestBindingFormForType","kind":"function","lang":"go","code":"func TestBindingFormForType(t *testing.T) {\n\ttestFormBindingForType(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"map_foo={\\\"bar\\\":123}\", \"map_foo=1\", \"Map\")\n\n\ttestFormBindingForType(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"slice_foo=1&slice_foo=2\", \"bar2=1&bar2=2\", \"Slice\")\n\n\ttestFormBindingForType(t, http.MethodGet,\n\t\t\"/?slice_foo=1&slice_foo=2\", \"/?bar2=1&bar2=2\",\n\t\t\"\", \"\", \"Slice\")\n\n\ttestFormBindingForType(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"slice_map_foo=1&slice_map_foo=2\", \"bar2=1&bar2=2\", \"SliceMap\")\n\n\ttestFormBindingForType(t, http.MethodGet,\n\t\t\"/?slice_map_foo=1&slice_map_foo=2\", \"/?bar2=1&bar2=2\",\n\t\t\"\", \"\", \"SliceMap\")\n\n\ttestFormBindingForType(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"ptr_bar=test\", \"bar2=test\", \"Ptr\")\n\n\ttestFormBindingForType(t, http.MethodGet,\n\t\t\"/?ptr_bar=test\", \"/?bar2=test\",\n\t\t\"\", \"\", \"Ptr\")\n\n\ttestFormBindingForType(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"idx=123\", \"id1=1\", \"Struct\")\n\n\ttestFormBindingForType(t, http.MethodGet,\n\t\t\"/?idx=123\", \"/?id1=1\",\n\t\t\"\", \"\", \"Struct\")\n\n\ttestFormBindingForType(t, http.MethodPost,\n\t\t\"/\", \"/\",\n\t\t\"name=thinkerou\", \"name1=ou\", \"StructPointer\")\n\n\ttestFormBindingForType(t, http.MethodGet,\n\t\t\"/?name=thinkerou\", \"/?name1=ou\",\n\t\t\"\", \"\", \"StructPointer\""} {"repo":"gin","file":"binding/binding_test.go","line":371,"symbol":"TestBindingFormStringMap","kind":"function","lang":"go","code":"func TestBindingFormStringMap(t *testing.T) {\n\ttestBodyBindingStringMap(t, Form,\n\t\t\"/\", \"\",\n\t\t`foo=bar&hello=world`, \"\")\n\t// Should pick the last value\n\ttestBodyBindingStringMap(t, Form,\n\t\t\"/\", \"\",\n\t\t`foo=something&foo=bar&hello=world`, \"\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":381,"symbol":"TestBindingFormStringSliceMap","kind":"function","lang":"go","code":"func TestBindingFormStringSliceMap(t *testing.T) {\n\tobj := make(map[string][]string)\n\treq := requestWithBody(http.MethodPost, \"/\", \"foo=something&foo=bar&hello=world\")\n\treq.Header.Add(\"Content-Type\", MIMEPOSTForm)\n\terr := Form.Bind(req, &obj)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, obj)\n\tassert.Len(t, obj, 2)\n\ttarget := map[string][]string{\n\t\t\"foo\": {\"something\", \"bar\"},\n\t\t\"hello\": {\"world\"},\n\t}\n\tassert.True(t, reflect.DeepEqual(obj, target))\n\n\tobjInvalid := make(map[string][]int)\n\treq = requestWithBody(http.MethodPost, \"/\", \"foo=something&foo=bar&hello=world\")\n\treq.Header.Add(\"Content-Type\", MIMEPOSTForm)\n\terr = Form.Bind(req, &objInvalid)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":402,"symbol":"TestBindingQuery","kind":"function","lang":"go","code":"func TestBindingQuery(t *testing.T) {\n\ttestQueryBinding(t, http.MethodPost,\n\t\t\"/?foo=bar&bar=foo\", \"/\",\n\t\t\"foo=unused\", \"bar2=foo\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":408,"symbol":"TestBindingQuery2","kind":"function","lang":"go","code":"func TestBindingQuery2(t *testing.T) {\n\ttestQueryBinding(t, http.MethodGet,\n\t\t\"/?foo=bar&bar=foo\", \"/?bar2=foo\",\n\t\t\"foo=unused\", \"\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":414,"symbol":"TestBindingQueryFail","kind":"function","lang":"go","code":"func TestBindingQueryFail(t *testing.T) {\n\ttestQueryBindingFail(t, http.MethodPost,\n\t\t\"/?map_foo=\", \"/\",\n\t\t\"map_foo=unused\", \"bar2=foo\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":420,"symbol":"TestBindingQueryFail2","kind":"function","lang":"go","code":"func TestBindingQueryFail2(t *testing.T) {\n\ttestQueryBindingFail(t, http.MethodGet,\n\t\t\"/?map_foo=\", \"/?bar2=foo\",\n\t\t\"map_foo=unused\", \"\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":426,"symbol":"TestBindingQueryBoolFail","kind":"function","lang":"go","code":"func TestBindingQueryBoolFail(t *testing.T) {\n\ttestQueryBindingBoolFail(t, http.MethodGet,\n\t\t\"/?bool_foo=fasl\", \"/?bar2=foo\",\n\t\t\"bool_foo=unused\", \"\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":432,"symbol":"TestBindingQueryStringMap","kind":"function","lang":"go","code":"func TestBindingQueryStringMap(t *testing.T) {\n\tb := Query\n\n\tobj := make(map[string]string)\n\treq := requestWithBody(http.MethodGet, \"/?foo=bar&hello=world\", \"\")\n\terr := b.Bind(req, &obj)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, obj)\n\tassert.Len(t, obj, 2)\n\tassert.Equal(t, \"bar\", obj[\"foo\"])\n\tassert.Equal(t, \"world\", obj[\"hello\"])\n\n\tobj = make(map[string]string)\n\treq = requestWithBody(http.MethodGet, \"/?foo=bar&foo=2&hello=world\", \"\") // should pick last\n\terr = b.Bind(req, &obj)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, obj)\n\tassert.Len(t, obj, 2)\n\tassert.Equal(t, \"2\", obj[\"foo\"])\n\tassert.Equal(t, \"world\", obj[\"hello\"])\n}"} {"repo":"gin","file":"binding/binding_test.go","line":454,"symbol":"TestBindingXML","kind":"function","lang":"go","code":"func TestBindingXML(t *testing.T) {\n\ttestBodyBinding(t,\n\t\tXML, \"xml\",\n\t\t\"/\", \"/\",\n\t\t\"bar\", \"foo\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":461,"symbol":"TestBindingXMLFail","kind":"function","lang":"go","code":"func TestBindingXMLFail(t *testing.T) {\n\ttestBodyBindingFail(t,\n\t\tXML, \"xml\",\n\t\t\"/\", \"/\",\n\t\t\"bar\", \"foo\")\n}"} {"repo":"gin","file":"binding/binding_test.go","line":468,"symbol":"TestBindingTOML","kind":"function","lang":"go","code":"func TestBindingTOML(t *testing.T) {\n\ttestBodyBinding(t,\n\t\tTOML, \"toml\",\n\t\t\"/\", \"/\",\n\t\t`foo=\"bar\"`, `bar=\"foo\"`)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":475,"symbol":"TestBindingTOMLFail","kind":"function","lang":"go","code":"func TestBindingTOMLFail(t *testing.T) {\n\ttestBodyBindingFail(t,\n\t\tTOML, \"toml\",\n\t\t\"/\", \"/\",\n\t\t`foo=\\n\"bar\"`, `bar=\"foo\"`)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":482,"symbol":"TestBindingYAML","kind":"function","lang":"go","code":"func TestBindingYAML(t *testing.T) {\n\ttestBodyBinding(t,\n\t\tYAML, \"yaml\",\n\t\t\"/\", \"/\",\n\t\t`foo: bar`, `bar: foo`)\n}"} {"repo":"gin","file":"binding/binding_test.go","line":489,"symbol":"TestBindingYAMLStringMap","kind":"function","lang":"go","code":"func TestBindingYAMLStringMap(t *testing.T) {\n\t// YAML is a superset of JSON, so the test below is JSON (to avoid newlines)\n\ttestBodyBindingStringMap(t, YAML,\n\t\t\"/\", \"/\",\n\t\t`{\"foo\": \"bar\", \"hello\": \"world\"}`, `{\"nested\": {\"foo\": \"bar\"}}`)\n}"} {"repo":"gin","file":"binding/bson.go","line":14,"symbol":"bsonBinding","kind":"type","lang":"go","code":"type bsonBinding struct{}"} {"repo":"gin","file":"binding/bson.go","line":16,"symbol":"Name","kind":"method","lang":"go","code":"func (bsonBinding) Name() string {\n\treturn \"bson\"\n}"} {"repo":"gin","file":"binding/bson.go","line":20,"symbol":"Bind","kind":"method","lang":"go","code":"func (b bsonBinding) Bind(req *http.Request, obj any) error {\n\tbuf, err := io.ReadAll(req.Body)\n\tif err == nil {\n\t\terr = b.BindBody(buf, obj)\n\t}\n\treturn err\n}"} {"repo":"gin","file":"binding/bson.go","line":28,"symbol":"BindBody","kind":"method","lang":"go","code":"func (bsonBinding) BindBody(body []byte, obj any) error {\n\treturn bson.Unmarshal(body, obj)\n}"} {"repo":"gin","file":"binding/default_validator.go","line":16,"symbol":"defaultValidator","kind":"type","lang":"go","code":"type defaultValidator struct {\n\tonce sync.Once\n\tvalidate *validator.Validate\n}"} {"repo":"gin","file":"binding/default_validator.go","line":21,"symbol":"SliceValidationError","kind":"type","lang":"go","code":"type SliceValidationError []error"} {"repo":"gin","file":"binding/default_validator.go","line":24,"symbol":"Error","kind":"method","lang":"go","doc":"Error concatenates all error elements in SliceValidationError into a single string separated by \\n.","code":"func (err SliceValidationError) Error() string {\n\tif len(err) == 0 {\n\t\treturn \"\"\n\t}\n\n\tvar b strings.Builder\n\tfor i := range len(err) {\n\t\tif err[i] != nil {\n\t\t\tif b.Len() > 0 {\n\t\t\t\tb.WriteString(\"\\n\")\n\t\t\t}\n\t\t\tb.WriteString(\"[\")\n\t\t\tb.WriteString(strconv.Itoa(i))\n\t\t\tb.WriteString(\"]: \")\n\t\t\tb.WriteString(err[i].Error())\n\t\t}\n\t}\n\treturn b.String()\n}"} {"repo":"gin","file":"binding/default_validator.go","line":29,"symbol":"b","kind":"variable","lang":"go","code":"b strings.Builder"} {"repo":"gin","file":"binding/default_validator.go","line":44,"symbol":"_","kind":"variable","lang":"go","code":"_ StructValidator = (*defaultValidator)(nil)"} {"repo":"gin","file":"binding/default_validator.go","line":47,"symbol":"ValidateStruct","kind":"method","lang":"go","doc":"ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.","code":"func (v *defaultValidator) ValidateStruct(obj any) error {\n\tif obj == nil {\n\t\treturn nil\n\t}\n\n\tvalue := reflect.ValueOf(obj)\n\tswitch value.Kind() {\n\tcase reflect.Ptr:\n\t\tif value.Elem().Kind() != reflect.Struct {\n\t\t\treturn v.ValidateStruct(value.Elem().Interface())\n\t\t}\n\t\treturn v.validateStruct(obj)\n\tcase reflect.Struct:\n\t\treturn v.validateStruct(obj)\n\tcase reflect.Slice, reflect.Array:\n\t\tcount := value.Len()\n\t\tvalidateRet := make(SliceValidationError, 0)\n\t\tfor i := range count {\n\t\t\tif err := v.ValidateStruct(value.Index(i).Interface()); err != nil {\n\t\t\t\tvalidateRet = append(validateRet, err)\n\t\t\t}\n\t\t}\n\t\tif len(validateRet) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\treturn validateRet\n\tdefault:\n\t\treturn nil\n\t}\n}"} {"repo":"gin","file":"binding/default_validator.go","line":79,"symbol":"validateStruct","kind":"method","lang":"go","doc":"validateStruct receives struct type","code":"func (v *defaultValidator) validateStruct(obj any) error {\n\tv.lazyinit()\n\treturn v.validate.Struct(obj)\n}"} {"repo":"gin","file":"binding/default_validator.go","line":88,"symbol":"Engine","kind":"method","lang":"go","doc":"Engine returns the underlying validator engine which powers the default Validator instance. This is useful if you want to register custom validations or struct level validations. See validator GoDoc for more info - https://pkg.go.dev/github.com/go-playground/validator/v10","code":"func (v *defaultValidator) Engine() any {\n\tv.lazyinit()\n\treturn v.validate\n}"} {"repo":"gin","file":"binding/default_validator.go","line":93,"symbol":"lazyinit","kind":"method","lang":"go","code":"func (v *defaultValidator) lazyinit() {\n\tv.once.Do(func() {\n\t\tv.validate = validator.New()\n\t\tv.validate.SetTagName(\"binding\")\n\t})\n}"} {"repo":"gin","file":"binding/default_validator_benchmark_test.go","line":13,"symbol":"BenchmarkSliceValidationError","kind":"function","lang":"go","code":"func BenchmarkSliceValidationError(b *testing.B) {\n\tconst size int = 100\n\te := make(SliceValidationError, size)\n\tfor j := 0; j < size; j++ {\n\t\te[j] = errors.New(strconv.Itoa(j))\n\t}\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tif len(e.Error()) == 0 {\n\t\t\tb.Errorf(\"error\")\n\t\t}\n\t}\n}"} {"repo":"gin","file":"binding/default_validator_benchmark_test.go","line":14,"symbol":"size","kind":"constant","lang":"go","code":"size int = 100"} {"repo":"gin","file":"binding/default_validator_test.go","line":12,"symbol":"TestSliceValidationError","kind":"function","lang":"go","code":"func TestSliceValidationError(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\terr SliceValidationError\n\t\twant string\n\t}{\n\t\t{\"has nil elements\", SliceValidationError{errors.New(\"test error\"), nil}, \"[0]: test error\"},\n\t\t{\"has zero elements\", SliceValidationError{}, \"\"},\n\t\t{\"has one element\", SliceValidationError{errors.New(\"test one error\")}, \"[0]: test one error\"},\n\t\t{\n\t\t\t\"has two elements\",\n\t\t\tSliceValidationError{\n\t\t\t\terrors.New(\"first error\"),\n\t\t\t\terrors.New(\"second error\"),\n\t\t\t},\n\t\t\t\"[0]: first error\\n[1]: second error\",\n\t\t},\n\t\t{\n\t\t\t\"has many elements\",\n\t\t\tSliceValidationError{\n\t\t\t\terrors.New(\"first error\"),\n\t\t\t\terrors.New(\"second error\"),\n\t\t\t\tnil,\n\t\t\t\tnil,\n\t\t\t\tnil,\n\t\t\t\terrors.New(\"last error\"),\n\t\t\t},\n\t\t\t\"[0]: first error\\n[1]: second error\\n[5]: last error\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := tt.err.Error(); got != tt.want {\n\t\t\t\tt.Errorf(\"SliceValidationError.Error() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}"} {"repo":"gin","file":"binding/default_validator_test.go","line":51,"symbol":"TestDefaultValidator","kind":"function","lang":"go","code":"func TestDefaultValidator(t *testing.T) {\n\ttype exampleStruct struct {\n\t\tA string `binding:\"max=8\"`\n\t\tB int `binding:\"gt=0\"`\n\t}\n\ttests := []struct {\n\t\tname string\n\t\tv *defaultValidator\n\t\tobj any\n\t\twantErr bool\n\t}{\n\t\t{\"validate nil obj\", &defaultValidator{}, nil, false},\n\t\t{\"validate int obj\", &defaultValidator{}, 3, false},\n\t\t{\"validate struct failed-1\", &defaultValidator{}, exampleStruct{A: \"123456789\", B: 1}, true},\n\t\t{\"validate struct failed-2\", &defaultValidator{}, exampleStruct{A: \"12345678\", B: 0}, true},\n\t\t{\"validate struct passed\", &defaultValidator{}, exampleStruct{A: \"12345678\", B: 1}, false},\n\t\t{\"validate *struct failed-1\", &defaultValidator{}, &exampleStruct{A: \"123456789\", B: 1}, true},\n\t\t{\"validate *struct failed-2\", &defaultValidator{}, &exampleStruct{A: \"12345678\", B: 0}, true},\n\t\t{\"validate *struct passed\", &defaultValidator{}, &exampleStruct{A: \"12345678\", B: 1}, false},\n\t\t{\"validate []struct failed-1\", &defaultValidator{}, []exampleStruct{{A: \"123456789\", B: 1}}, true},\n\t\t{\"validate []struct failed-2\", &defaultValidator{}, []exampleStruct{{A: \"12345678\", B: 0}}, true},\n\t\t{\"validate []struct passed\", &defaultValidator{}, []exampleStruct{{A: \"123456"} {"repo":"gin","file":"binding/default_validator_test.go","line":52,"symbol":"exampleStruct","kind":"type","lang":"go","code":"type exampleStruct struct {\n\t\tA string `binding:\"max=8\"`\n\t\tB int `binding:\"gt=0\"`\n\t}"} {"repo":"gin","file":"binding/form.go","line":12,"symbol":"defaultMemory","kind":"constant","lang":"go","code":"defaultMemory = 32 << 20"} {"repo":"gin","file":"binding/form.go","line":14,"symbol":"formBinding","kind":"type","lang":"go","code":"type (\n\tformBinding struct{}\n\tformPostBinding struct{}\n\tformMultipartBinding struct{}\n)"} {"repo":"gin","file":"binding/form.go","line":14,"symbol":"formPostBinding","kind":"type","lang":"go","code":"type (\n\tformBinding struct{}\n\tformPostBinding struct{}\n\tformMultipartBinding struct{}\n)"} {"repo":"gin","file":"binding/form.go","line":14,"symbol":"formMultipartBinding","kind":"type","lang":"go","code":"type (\n\tformBinding struct{}\n\tformPostBinding struct{}\n\tformMultipartBinding struct{}\n)"} {"repo":"gin","file":"binding/form.go","line":20,"symbol":"Name","kind":"method","lang":"go","code":"func (formBinding) Name() string {\n\treturn \"form\"\n}"} {"repo":"gin","file":"binding/form.go","line":24,"symbol":"Bind","kind":"method","lang":"go","code":"func (formBinding) Bind(req *http.Request, obj any) error {\n\tif err := req.ParseForm(); err != nil {\n\t\treturn err\n\t}\n\tif err := req.ParseMultipartForm(defaultMemory); err != nil && !errors.Is(err, http.ErrNotMultipart) {\n\t\treturn err\n\t}\n\tif err := mapForm(obj, req.Form); err != nil {\n\t\treturn err\n\t}\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/form.go","line":37,"symbol":"Name","kind":"method","lang":"go","code":"func (formPostBinding) Name() string {\n\treturn \"form-urlencoded\"\n}"} {"repo":"gin","file":"binding/form.go","line":41,"symbol":"Bind","kind":"method","lang":"go","code":"func (formPostBinding) Bind(req *http.Request, obj any) error {\n\tif err := req.ParseForm(); err != nil {\n\t\treturn err\n\t}\n\tif err := mapForm(obj, req.PostForm); err != nil {\n\t\treturn err\n\t}\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/form.go","line":51,"symbol":"Name","kind":"method","lang":"go","code":"func (formMultipartBinding) Name() string {\n\treturn \"multipart/form-data\"\n}"} {"repo":"gin","file":"binding/form.go","line":55,"symbol":"Bind","kind":"method","lang":"go","code":"func (formMultipartBinding) Bind(req *http.Request, obj any) error {\n\tif err := req.ParseMultipartForm(defaultMemory); err != nil {\n\t\treturn err\n\t}\n\tif err := mappingByPtr(obj, (*multipartRequest)(req), \"form\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":23,"symbol":"errUnknownType","kind":"variable","lang":"go","code":"errUnknownType = errors.New(\"unknown type\")"} {"repo":"gin","file":"binding/form_mapping.go","line":26,"symbol":"ErrConvertMapStringSlice","kind":"variable","lang":"go","doc":"ErrConvertMapStringSlice can not convert to map[string][]string","code":"ErrConvertMapStringSlice = errors.New(\"can not convert to map slices of strings\")"} {"repo":"gin","file":"binding/form_mapping.go","line":29,"symbol":"ErrConvertToMapString","kind":"variable","lang":"go","doc":"ErrConvertToMapString can not convert to map[string]string","code":"ErrConvertToMapString = errors.New(\"can not convert to map of strings\")"} {"repo":"gin","file":"binding/form_mapping.go","line":32,"symbol":"mapURI","kind":"function","lang":"go","code":"func mapURI(ptr any, m map[string][]string) error {\n\treturn mapFormByTag(ptr, m, \"uri\")\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":36,"symbol":"mapForm","kind":"function","lang":"go","code":"func mapForm(ptr any, form map[string][]string) error {\n\treturn mapFormByTag(ptr, form, \"form\")\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":40,"symbol":"MapFormWithTag","kind":"function","lang":"go","code":"func MapFormWithTag(ptr any, form map[string][]string, tag string) error {\n\treturn mapFormByTag(ptr, form, tag)\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":44,"symbol":"emptyField","kind":"variable","lang":"go","code":"emptyField = reflect.StructField{}"} {"repo":"gin","file":"binding/form_mapping.go","line":46,"symbol":"mapFormByTag","kind":"function","lang":"go","code":"func mapFormByTag(ptr any, form map[string][]string, tag string) error {\n\t// Check if ptr is a map\n\tptrVal := reflect.ValueOf(ptr)\n\tvar pointed any\n\tif ptrVal.Kind() == reflect.Ptr {\n\t\tptrVal = ptrVal.Elem()\n\t\tpointed = ptrVal.Interface()\n\t}\n\tif ptrVal.Kind() == reflect.Map &&\n\t\tptrVal.Type().Key().Kind() == reflect.String {\n\t\tif pointed != nil {\n\t\t\tptr = pointed\n\t\t}\n\t\treturn setFormMap(ptr, form)\n\t}\n\n\treturn mappingByPtr(ptr, formSource(form), tag)\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":49,"symbol":"pointed","kind":"variable","lang":"go","code":"pointed any"} {"repo":"gin","file":"binding/form_mapping.go","line":66,"symbol":"setter","kind":"type","lang":"go","doc":"setter tries to set value on a walking by fields of a struct","code":"type setter interface {\n\tTrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (isSet bool, err error)\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":70,"symbol":"formSource","kind":"type","lang":"go","code":"type formSource map[string][]string"} {"repo":"gin","file":"binding/form_mapping.go","line":72,"symbol":"_","kind":"variable","lang":"go","code":"_ setter = formSource(nil)"} {"repo":"gin","file":"binding/form_mapping.go","line":75,"symbol":"TrySet","kind":"method","lang":"go","doc":"TrySet tries to set a value by request's form source (like map[string][]string)","code":"func (form formSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSet bool, err error) {\n\treturn setByForm(value, field, form, tagValue, opt)\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":79,"symbol":"mappingByPtr","kind":"function","lang":"go","code":"func mappingByPtr(ptr any, setter setter, tag string) error {\n\t_, err := mapping(reflect.ValueOf(ptr), emptyField, setter, tag)\n\treturn err\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":84,"symbol":"mapping","kind":"function","lang":"go","code":"func mapping(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) {\n\tif field.Tag.Get(tag) == \"-\" { // just ignoring this field\n\t\treturn false, nil\n\t}\n\n\tvKind := value.Kind()\n\n\tif vKind == reflect.Ptr {\n\t\tvar isNew bool\n\t\tvPtr := value\n\t\tif value.IsNil() {\n\t\t\tisNew = true\n\t\t\tvPtr = reflect.New(value.Type().Elem())\n\t\t}\n\t\tisSet, err := mapping(vPtr.Elem(), field, setter, tag)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif isNew && isSet {\n\t\t\tvalue.Set(vPtr)\n\t\t}\n\t\treturn isSet, nil\n\t}\n\n\tif vKind != reflect.Struct || !field.Anonymous {\n\t\tok, err := tryToSetValue(value, field, setter, tag)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif ok {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\tif vKind == reflect.Struct {\n\t\ttValue := value.Type()\n\n\t\tvar isSet bool\n\t\tfor i := range value.NumField() {\n\t\t\tsf := tValue.Field(i)\n\t\t\tif sf.PkgPath != \"\" && !sf.Anonymous { // unexported\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tok, err := mapping(value.Field(i), sf, setter, tag)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tisSet = isSet || ok\n\t\t}\n\t\treturn isSet, nil\n\t}\n\treturn false, nil\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":92,"symbol":"isNew","kind":"variable","lang":"go","code":"isNew bool"} {"repo":"gin","file":"binding/form_mapping.go","line":121,"symbol":"isSet","kind":"variable","lang":"go","code":"isSet bool"} {"repo":"gin","file":"binding/form_mapping.go","line":138,"symbol":"setOptions","kind":"type","lang":"go","code":"type setOptions struct {\n\tisDefaultExists bool\n\tdefaultValue string\n\t// parser specifies what interface to use for reading the request & default values (e.g. `encoding.TextUnmarshaler`)\n\tparser string\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":145,"symbol":"tryToSetValue","kind":"function","lang":"go","code":"func tryToSetValue(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) {\n\tvar tagValue string\n\tvar setOpt setOptions\n\n\ttagValue = field.Tag.Get(tag)\n\ttagValue, opts := head(tagValue, \",\")\n\n\tif tagValue == \"\" { // default value is FieldName\n\t\ttagValue = field.Name\n\t}\n\tif tagValue == \"\" { // when field is \"emptyField\" variable\n\t\treturn false, nil\n\t}\n\n\tvar opt string\n\tfor len(opts) > 0 {\n\t\topt, opts = head(opts, \",\")\n\n\t\tif k, v := head(opt, \"=\"); k == \"default\" {\n\t\t\tsetOpt.isDefaultExists = true\n\t\t\tsetOpt.defaultValue = v\n\n\t\t\t// convert semicolon-separated default values to csv-separated values for processing in setByForm\n\t\t\tif field.Type.Kind() == reflect.Slice || field.Type.Kind() == reflect.Array {\n\t\t\t\tcfTag := field.Tag.Get(\"collection_format\")\n\t\t\t\tif cfTag == \"\" || cfTag == \"multi\" || cfTag == \"csv\" {\n\t\t\t\t\tsetOpt.defaultValue = strings.ReplaceAll(v, \";\", \",\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else if k, v = head(opt, \"=\"); k == \"parser\" {\n\t\t\tsetOpt.parser = v\n\t\t}\n\t}\n\n\treturn setter.TrySet(value, field, tagValue, setOpt)\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":146,"symbol":"tagValue","kind":"variable","lang":"go","code":"tagValue string"} {"repo":"gin","file":"binding/form_mapping.go","line":147,"symbol":"setOpt","kind":"variable","lang":"go","code":"setOpt setOptions"} {"repo":"gin","file":"binding/form_mapping.go","line":159,"symbol":"opt","kind":"variable","lang":"go","code":"opt string"} {"repo":"gin","file":"binding/form_mapping.go","line":183,"symbol":"BindUnmarshaler","kind":"type","lang":"go","doc":"BindUnmarshaler is the interface used to wrap the UnmarshalParam method.","code":"type BindUnmarshaler interface {\n\t// UnmarshalParam decodes and assigns a value from a form or query param.\n\tUnmarshalParam(param string) error\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":191,"symbol":"trySetCustom","kind":"function","lang":"go","doc":"trySetCustom tries to set a custom type value If the value implements the BindUnmarshaler interface, it will be used to set the value, we will return `true` to skip the default value setting.","code":"func trySetCustom(val string, value reflect.Value) (isSet bool, err error) {\n\tswitch v := value.Addr().Interface().(type) {\n\tcase BindUnmarshaler:\n\t\treturn true, v.UnmarshalParam(val)\n\t}\n\treturn false, nil\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":201,"symbol":"trySetUsingParser","kind":"function","lang":"go","doc":"trySetUsingParser tries to set a custom type value based on the presence of the \"parser\" tag on the field. If the parser tag does not exist or does not match any of the supported parsers, gin will skip over this.","code":"func trySetUsingParser(val string, value reflect.Value, parser string) (isSet bool, err error) {\n\tswitch parser {\n\tcase \"encoding.TextUnmarshaler\":\n\t\tv, ok := value.Addr().Interface().(encoding.TextUnmarshaler)\n\t\tif !ok {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, v.UnmarshalText([]byte(val))\n\t}\n\treturn false, nil\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":213,"symbol":"trySplit","kind":"function","lang":"go","code":"func trySplit(vs []string, field reflect.StructField) (newVs []string, err error) {\n\tcfTag := field.Tag.Get(\"collection_format\")\n\tif cfTag == \"\" || cfTag == \"multi\" {\n\t\treturn vs, nil\n\t}\n\n\tvar sep string\n\tswitch cfTag {\n\tcase \"csv\":\n\t\tsep = \",\"\n\tcase \"ssv\":\n\t\tsep = \" \"\n\tcase \"tsv\":\n\t\tsep = \"\\t\"\n\tcase \"pipes\":\n\t\tsep = \"|\"\n\tdefault:\n\t\treturn vs, fmt.Errorf(\"%s is not supported in the collection_format. (multi, csv, ssv, tsv, pipes)\", cfTag)\n\t}\n\n\ttotalLength := 0\n\tfor _, v := range vs {\n\t\ttotalLength += strings.Count(v, sep) + 1\n\t}\n\tnewVs = make([]string, 0, totalLength)\n\tfor _, v := range vs {\n\t\tnewVs = append(newVs, strings.Split(v, sep)...)\n\t}\n\n\treturn newVs, nil\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":219,"symbol":"sep","kind":"variable","lang":"go","code":"sep string"} {"repo":"gin","file":"binding/form_mapping.go","line":245,"symbol":"setByForm","kind":"function","lang":"go","code":"func setByForm(value reflect.Value, field reflect.StructField, form map[string][]string, tagValue string, opt setOptions) (isSet bool, err error) {\n\tvs, ok := form[tagValue]\n\tif !ok && !opt.isDefaultExists {\n\t\treturn false, nil\n\t}\n\n\tswitch value.Kind() {\n\tcase reflect.Slice:\n\t\tif len(vs) == 0 {\n\t\t\tif !opt.isDefaultExists {\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tvs = []string{opt.defaultValue}\n\t\t\t// pre-process the default value for multi if present\n\t\t\tcfTag := field.Tag.Get(\"collection_format\")\n\t\t\tif cfTag == \"\" || cfTag == \"multi\" {\n\t\t\t\tvs = strings.Split(opt.defaultValue, \",\")\n\t\t\t}\n\t\t}\n\n\t\tif ok, err = trySetUsingParser(vs[0], value, opt.parser); ok {\n\t\t\treturn ok, err\n\t\t} else if ok, err = trySetCustom(vs[0], value); ok {\n\t\t\treturn ok, err\n\t\t}\n\n\t\tif vs, err = trySplit(vs, field); err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\treturn true, setSlice(vs, value, field, opt)\n\tcase reflect.Array:\n\t\tif len(vs) == 0 {\n\t\t\tif !opt.isDefaultExists {\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tvs = []string{opt.defaultValue}\n\t\t\t// pre-process the default value for multi if present\n\t\t\tcfTag := field.Tag.Get(\"collection_format\")\n\t\t\tif cfTag == \"\" || cfTag == \"multi\" {\n\t\t\t\tvs = strings.Split(opt.defaultValue, \",\")\n\t\t\t}\n\t"} {"repo":"gin","file":"binding/form_mapping.go","line":307,"symbol":"val","kind":"variable","lang":"go","code":"val string"} {"repo":"gin","file":"binding/form_mapping.go","line":323,"symbol":"setWithProperType","kind":"function","lang":"go","code":"func setWithProperType(val string, value reflect.Value, field reflect.StructField, opt setOptions) error {\n\t// this if-check is required for parsing nested types like []MyId, where MyId is [12]byte\n\tif ok, err := trySetUsingParser(val, value, opt.parser); ok {\n\t\treturn err\n\t} else if ok, err = trySetCustom(val, value); ok {\n\t\treturn err\n\t}\n\n\t// If it is a string type, no spaces are removed, and the user data is not modified here\n\tif value.Kind() != reflect.String {\n\t\tval = strings.TrimSpace(val)\n\t}\n\n\tswitch value.Kind() {\n\tcase reflect.Int:\n\t\treturn setIntField(val, 0, value)\n\tcase reflect.Int8:\n\t\treturn setIntField(val, 8, value)\n\tcase reflect.Int16:\n\t\treturn setIntField(val, 16, value)\n\tcase reflect.Int32:\n\t\treturn setIntField(val, 32, value)\n\tcase reflect.Int64:\n\t\tswitch value.Interface().(type) {\n\t\tcase time.Duration:\n\t\t\treturn setTimeDuration(val, value)\n\t\t}\n\t\treturn setIntField(val, 64, value)\n\tcase reflect.Uint:\n\t\treturn setUintField(val, 0, value)\n\tcase reflect.Uint8:\n\t\treturn setUintField(val, 8, value)\n\tcase reflect.Uint16:\n\t\treturn setUintField(val, 16, value)\n\tcase reflect.Uint32:\n\t\treturn setUintField(val, 32, value)\n\tcase reflect.Uint64:\n\t\treturn setUintField(val, 64,"} {"repo":"gin","file":"binding/form_mapping.go","line":390,"symbol":"setIntField","kind":"function","lang":"go","code":"func setIntField(val string, bitSize int, field reflect.Value) error {\n\tif val == \"\" {\n\t\tval = \"0\"\n\t}\n\tintVal, err := strconv.ParseInt(val, 10, bitSize)\n\tif err == nil {\n\t\tfield.SetInt(intVal)\n\t}\n\treturn err\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":401,"symbol":"setUintField","kind":"function","lang":"go","code":"func setUintField(val string, bitSize int, field reflect.Value) error {\n\tif val == \"\" {\n\t\tval = \"0\"\n\t}\n\tuintVal, err := strconv.ParseUint(val, 10, bitSize)\n\tif err == nil {\n\t\tfield.SetUint(uintVal)\n\t}\n\treturn err\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":412,"symbol":"setBoolField","kind":"function","lang":"go","code":"func setBoolField(val string, field reflect.Value) error {\n\tif val == \"\" {\n\t\tval = \"false\"\n\t}\n\tboolVal, err := strconv.ParseBool(val)\n\tif err == nil {\n\t\tfield.SetBool(boolVal)\n\t}\n\treturn err\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":423,"symbol":"setFloatField","kind":"function","lang":"go","code":"func setFloatField(val string, bitSize int, field reflect.Value) error {\n\tif val == \"\" {\n\t\tval = \"0.0\"\n\t}\n\tfloatVal, err := strconv.ParseFloat(val, bitSize)\n\tif err == nil {\n\t\tfield.SetFloat(floatVal)\n\t}\n\treturn err\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":434,"symbol":"setTimeField","kind":"function","lang":"go","code":"func setTimeField(val string, structField reflect.StructField, value reflect.Value) error {\n\ttimeFormat := structField.Tag.Get(\"time_format\")\n\tif timeFormat == \"\" {\n\t\ttimeFormat = time.RFC3339\n\t}\n\n\tif val == \"\" {\n\t\tvalue.Set(reflect.ValueOf(time.Time{}))\n\t\treturn nil\n\t}\n\n\tswitch tf := strings.ToLower(timeFormat); tf {\n\tcase \"unix\", \"unixmilli\", \"unixmicro\", \"unixnano\":\n\t\ttv, err := strconv.ParseInt(val, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar t time.Time\n\t\tswitch tf {\n\t\tcase \"unix\":\n\t\t\tt = time.Unix(tv, 0)\n\t\tcase \"unixmilli\":\n\t\t\tt = time.UnixMilli(tv)\n\t\tcase \"unixmicro\":\n\t\t\tt = time.UnixMicro(tv)\n\t\tdefault:\n\t\t\tt = time.Unix(0, tv)\n\t\t}\n\n\t\tvalue.Set(reflect.ValueOf(t))\n\t\treturn nil\n\t}\n\n\tl := time.Local\n\tif isUTC, _ := strconv.ParseBool(structField.Tag.Get(\"time_utc\")); isUTC {\n\t\tl = time.UTC\n\t}\n\n\tif locTag := structField.Tag.Get(\"time_location\"); locTag != \"\" {\n\t\tloc, err := time.LoadLocation(locTag)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tl = loc\n\t}\n\n\tt, err := time.ParseInLocation(timeFormat, val, l)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalue.Set(reflect.ValueOf(t))\n\treturn nil\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":452,"symbol":"t","kind":"variable","lang":"go","code":"t time.Time"} {"repo":"gin","file":"binding/form_mapping.go","line":490,"symbol":"setArray","kind":"function","lang":"go","code":"func setArray(vals []string, value reflect.Value, field reflect.StructField, opt setOptions) error {\n\tfor i, s := range vals {\n\t\terr := setWithProperType(s, value.Index(i), field, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":500,"symbol":"setSlice","kind":"function","lang":"go","code":"func setSlice(vals []string, value reflect.Value, field reflect.StructField, opt setOptions) error {\n\tslice := reflect.MakeSlice(value.Type(), len(vals), len(vals))\n\terr := setArray(vals, slice, field, opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalue.Set(slice)\n\treturn nil\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":510,"symbol":"setTimeDuration","kind":"function","lang":"go","code":"func setTimeDuration(val string, value reflect.Value) error {\n\tif val == \"\" {\n\t\tval = \"0\"\n\t}\n\n\td, err := time.ParseDuration(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalue.Set(reflect.ValueOf(d))\n\treturn nil\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":523,"symbol":"head","kind":"function","lang":"go","code":"func head(str, sep string) (head string, tail string) {\n\thead, tail, _ = strings.Cut(str, sep)\n\treturn head, tail\n}"} {"repo":"gin","file":"binding/form_mapping.go","line":528,"symbol":"setFormMap","kind":"function","lang":"go","code":"func setFormMap(ptr any, form map[string][]string) error {\n\tel := reflect.TypeOf(ptr).Elem()\n\n\tif el.Kind() == reflect.Slice {\n\t\tptrMap, ok := ptr.(map[string][]string)\n\t\tif !ok {\n\t\t\treturn ErrConvertMapStringSlice\n\t\t}\n\t\tmaps.Copy(ptrMap, form)\n\n\t\treturn nil\n\t}\n\n\tptrMap, ok := ptr.(map[string]string)\n\tif !ok {\n\t\treturn ErrConvertToMapString\n\t}\n\tfor k, v := range form {\n\t\tptrMap[k] = v[len(v)-1] // pick last\n\t}\n\n\treturn nil\n}"} {"repo":"gin","file":"binding/form_mapping_benchmark_test.go","line":14,"symbol":"form","kind":"variable","lang":"go","code":"form = map[string][]string{\n\t\"name\": {\"mike\"},\n\t\"friends\": {\"anna\", \"nicole\"},\n\t\"id_number\": {\"12345678\"},\n\t\"id_date\": {\"2018-01-20\"},\n}"} {"repo":"gin","file":"binding/form_mapping_benchmark_test.go","line":21,"symbol":"structFull","kind":"type","lang":"go","code":"type structFull struct {\n\tName string `form:\"name\"`\n\tAge int `form:\"age,default=25\"`\n\tFriends []string `form:\"friends\"`\n\tID *struct {\n\t\tNumber string `form:\"id_number\"`\n\t\tDateOfIssue time.Time `form:\"id_date\" time_format:\"2006-01-02\" time_utc:\"true\"`\n\t}\n\tNationality *string `form:\"nationality\"`\n}"} {"repo":"gin","file":"binding/form_mapping_benchmark_test.go","line":32,"symbol":"BenchmarkMapFormFull","kind":"function","lang":"go","code":"func BenchmarkMapFormFull(b *testing.B) {\n\tvar s structFull\n\tfor b.Loop() {\n\t\terr := mapForm(&s, form)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"Error on a form mapping\")\n\t\t}\n\t}\n\tb.StopTimer()\n\n\tt := b\n\tassert.Equal(t, \"mike\", s.Name)\n\tassert.Equal(t, 25, s.Age)\n\tassert.Equal(t, []string{\"anna\", \"nicole\"}, s.Friends)\n\tassert.Equal(t, \"12345678\", s.ID.Number)\n\tassert.Equal(t, time.Date(2018, 1, 20, 0, 0, 0, 0, time.UTC), s.ID.DateOfIssue)\n\tassert.Nil(t, s.Nationality)\n}"} {"repo":"gin","file":"binding/form_mapping_benchmark_test.go","line":33,"symbol":"s","kind":"variable","lang":"go","code":"s structFull"} {"repo":"gin","file":"binding/form_mapping_benchmark_test.go","line":51,"symbol":"structName","kind":"type","lang":"go","code":"type structName struct {\n\tName string `form:\"name\"`\n}"} {"repo":"gin","file":"binding/form_mapping_benchmark_test.go","line":55,"symbol":"BenchmarkMapFormName","kind":"function","lang":"go","code":"func BenchmarkMapFormName(b *testing.B) {\n\tvar s structName\n\tfor b.Loop() {\n\t\terr := mapForm(&s, form)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"Error on a form mapping\")\n\t\t}\n\t}\n\tb.StopTimer()\n\n\tt := b\n\tassert.Equal(t, \"mike\", s.Name)\n}"} {"repo":"gin","file":"binding/form_mapping_benchmark_test.go","line":56,"symbol":"s","kind":"variable","lang":"go","code":"s structName"} {"repo":"gin","file":"binding/form_mapping_test.go","line":22,"symbol":"TestMappingBaseTypes","kind":"function","lang":"go","code":"func TestMappingBaseTypes(t *testing.T) {\n\tintPtr := func(i int) *int {\n\t\treturn &i\n\t}\n\tfor _, tt := range []struct {\n\t\tname string\n\t\tvalue any\n\t\tform string\n\t\texpect any\n\t}{\n\t\t{\"base type\", struct{ F int }{}, \"9\", int(9)},\n\t\t{\"base type\", struct{ F int8 }{}, \"9\", int8(9)},\n\t\t{\"base type\", struct{ F int16 }{}, \"9\", int16(9)},\n\t\t{\"base type\", struct{ F int32 }{}, \"9\", int32(9)},\n\t\t{\"base type\", struct{ F int64 }{}, \"9\", int64(9)},\n\t\t{\"base type\", struct{ F uint }{}, \"9\", uint(9)},\n\t\t{\"base type\", struct{ F uint8 }{}, \"9\", uint8(9)},\n\t\t{\"base type\", struct{ F uint16 }{}, \"9\", uint16(9)},\n\t\t{\"base type\", struct{ F uint32 }{}, \"9\", uint32(9)},\n\t\t{\"base type\", struct{ F uint64 }{}, \"9\", uint64(9)},\n\t\t{\"base type\", struct{ F bool }{}, \"True\", true},\n\t\t{\"base type\", struct{ F float32 }{}, \"9.1\", float32(9.1)},\n\t\t{\"base type\", struct{ F float64 }{}, \"9.1\", float64(9.1)},\n\t\t{\"base type\", struct{ F string }{}, \"test\", string(\"test\")},\n\t\t{\"base type\", struct{ F *int }{}, \"9\", intPtr(9)},\n\n\t\t// zero values\n\t\t{\"zero value\", struct{ F int }{}, \"\", int(0)},\n\t\t{\"zero value\", struct{ F uint }{}, \"\", uint(0)},\n\t\t{\"zero value\", struct{ F bool }{}, \"\", false},\n\t\t{\"zero value\", struct{ F float32 }"} {"repo":"gin","file":"binding/form_mapping_test.go","line":71,"symbol":"TestMappingDefault","kind":"function","lang":"go","code":"func TestMappingDefault(t *testing.T) {\n\tvar s struct {\n\t\tStr string `form:\",default=defaultVal\"`\n\t\tInt int `form:\",default=9\"`\n\t\tSlice []int `form:\",default=9\"`\n\t\tArray [1]int `form:\",default=9\"`\n\t}\n\terr := mappingByPtr(&s, formSource{}, \"form\")\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, \"defaultVal\", s.Str)\n\tassert.Equal(t, 9, s.Int)\n\tassert.Equal(t, []int{9}, s.Slice)\n\tassert.Equal(t, [1]int{9}, s.Array)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":72,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tStr string `form:\",default=defaultVal\"`\n\t\tInt int `form:\",default=9\"`\n\t\tSlice []int `form:\",default=9\"`\n\t\tArray [1]int `form:\",default=9\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":87,"symbol":"TestMappingSkipField","kind":"function","lang":"go","code":"func TestMappingSkipField(t *testing.T) {\n\tvar s struct {\n\t\tA int\n\t}\n\terr := mappingByPtr(&s, formSource{}, \"form\")\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, 0, s.A)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":88,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tA int\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":97,"symbol":"TestMappingIgnoreField","kind":"function","lang":"go","code":"func TestMappingIgnoreField(t *testing.T) {\n\tvar s struct {\n\t\tA int `form:\"A\"`\n\t\tB int `form:\"-\"`\n\t}\n\terr := mappingByPtr(&s, formSource{\"A\": {\"9\"}, \"B\": {\"9\"}}, \"form\")\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, 9, s.A)\n\tassert.Equal(t, 0, s.B)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":98,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tA int `form:\"A\"`\n\t\tB int `form:\"-\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":109,"symbol":"TestMappingUnexportedField","kind":"function","lang":"go","code":"func TestMappingUnexportedField(t *testing.T) {\n\tvar s struct {\n\t\tA int `form:\"a\"`\n\t\tb int `form:\"b\"`\n\t}\n\terr := mappingByPtr(&s, formSource{\"a\": {\"9\"}, \"b\": {\"9\"}}, \"form\")\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, 9, s.A)\n\tassert.Equal(t, 0, s.b)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":110,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tA int `form:\"a\"`\n\t\tb int `form:\"b\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":121,"symbol":"TestMappingPrivateField","kind":"function","lang":"go","code":"func TestMappingPrivateField(t *testing.T) {\n\tvar s struct {\n\t\tf int `form:\"field\"`\n\t}\n\terr := mappingByPtr(&s, formSource{\"field\": {\"6\"}}, \"form\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, 0, s.f)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":122,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tf int `form:\"field\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":130,"symbol":"TestMappingUnknownFieldType","kind":"function","lang":"go","code":"func TestMappingUnknownFieldType(t *testing.T) {\n\tvar s struct {\n\t\tU uintptr\n\t}\n\n\terr := mappingByPtr(&s, formSource{\"U\": {\"unknown\"}}, \"form\")\n\trequire.Error(t, err)\n\tassert.Equal(t, errUnknownType, err)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":131,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tU uintptr\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":140,"symbol":"TestMappingURI","kind":"function","lang":"go","code":"func TestMappingURI(t *testing.T) {\n\tvar s struct {\n\t\tF int `uri:\"field\"`\n\t}\n\terr := mapURI(&s, map[string][]string{\"field\": {\"6\"}})\n\trequire.NoError(t, err)\n\tassert.Equal(t, 6, s.F)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":141,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tF int `uri:\"field\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":149,"symbol":"TestMappingForm","kind":"function","lang":"go","code":"func TestMappingForm(t *testing.T) {\n\tvar s struct {\n\t\tF int `form:\"field\"`\n\t}\n\terr := mapForm(&s, map[string][]string{\"field\": {\"6\"}})\n\trequire.NoError(t, err)\n\tassert.Equal(t, 6, s.F)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":150,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tF int `form:\"field\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":158,"symbol":"TestMappingFormFieldNotSent","kind":"function","lang":"go","code":"func TestMappingFormFieldNotSent(t *testing.T) {\n\tvar s struct {\n\t\tF string `form:\"field,default=defVal\"`\n\t}\n\terr := mapForm(&s, map[string][]string{})\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"defVal\", s.F)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":159,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tF string `form:\"field,default=defVal\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":167,"symbol":"TestMappingFormWithEmptyToDefault","kind":"function","lang":"go","code":"func TestMappingFormWithEmptyToDefault(t *testing.T) {\n\tvar s struct {\n\t\tF string `form:\"field,default=DefVal\"`\n\t}\n\terr := mapForm(&s, map[string][]string{\"field\": {\"\"}})\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"DefVal\", s.F)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":168,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tF string `form:\"field,default=DefVal\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":176,"symbol":"TestMapFormWithTag","kind":"function","lang":"go","code":"func TestMapFormWithTag(t *testing.T) {\n\tvar s struct {\n\t\tF int `externalTag:\"field\"`\n\t}\n\terr := MapFormWithTag(&s, map[string][]string{\"field\": {\"6\"}}, \"externalTag\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, 6, s.F)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":177,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tF int `externalTag:\"field\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":185,"symbol":"TestMappingTime","kind":"function","lang":"go","code":"func TestMappingTime(t *testing.T) {\n\tvar s struct {\n\t\tTime time.Time\n\t\tLocalTime time.Time `time_format:\"2006-01-02\"`\n\t\tZeroValue time.Time\n\t\tCSTTime time.Time `time_format:\"2006-01-02\" time_location:\"Asia/Shanghai\"`\n\t\tUTCTime time.Time `time_format:\"2006-01-02\" time_utc:\"1\"`\n\t}\n\n\tvar err error\n\ttime.Local, err = time.LoadLocation(\"Europe/Berlin\")\n\trequire.NoError(t, err)\n\n\terr = mapForm(&s, map[string][]string{\n\t\t\"Time\": {\"2019-01-20T16:02:58Z\"},\n\t\t\"LocalTime\": {\"2019-01-20\"},\n\t\t\"ZeroValue\": {},\n\t\t\"CSTTime\": {\"2019-01-20\"},\n\t\t\"UTCTime\": {\"2019-01-20\"},\n\t})\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, \"2019-01-20 16:02:58 +0000 UTC\", s.Time.String())\n\tassert.Equal(t, \"2019-01-20 00:00:00 +0100 CET\", s.LocalTime.String())\n\tassert.Equal(t, \"2019-01-19 23:00:00 +0000 UTC\", s.LocalTime.UTC().String())\n\tassert.Equal(t, \"0001-01-01 00:00:00 +0000 UTC\", s.ZeroValue.String())\n\tassert.Equal(t, \"2019-01-20 00:00:00 +0800 CST\", s.CSTTime.String())\n\tassert.Equal(t, \"2019-01-19 16:00:00 +0000 UTC\", s.CSTTime.UTC().String())\n\tassert.Equal(t, \"2019-01-20 00:00:00 +0000 UTC\", s.UTCTime.String())\n\n\t// wrong location\n\tvar wrongLoc struct {\n\t\tTime time.Time `time_location:\"wrong\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":186,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tTime time.Time\n\t\tLocalTime time.Time `time_format:\"2006-01-02\"`\n\t\tZeroValue time.Time\n\t\tCSTTime time.Time `time_format:\"2006-01-02\" time_location:\"Asia/Shanghai\"`\n\t\tUTCTime time.Time `time_format:\"2006-01-02\" time_utc:\"1\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":194,"symbol":"err","kind":"variable","lang":"go","code":"err error"} {"repo":"gin","file":"binding/form_mapping_test.go","line":216,"symbol":"wrongLoc","kind":"variable","lang":"go","doc":"wrong location","code":"wrongLoc struct {\n\t\tTime time.Time `time_location:\"wrong\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":223,"symbol":"wrongTime","kind":"variable","lang":"go","doc":"wrong time value","code":"wrongTime struct {\n\t\tTime time.Time\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":230,"symbol":"bindTestData","kind":"type","lang":"go","code":"type bindTestData struct {\n\tneed any\n\tgot any\n\tin map[string][]string\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":236,"symbol":"TestMappingTimeUnixNano","kind":"function","lang":"go","code":"func TestMappingTimeUnixNano(t *testing.T) {\n\ttype needFixUnixNanoEmpty struct {\n\t\tCreateTime time.Time `form:\"createTime\" time_format:\"unixNano\"`\n\t}\n\n\t// ok\n\ttests := []bindTestData{\n\t\t{need: &needFixUnixNanoEmpty{}, got: &needFixUnixNanoEmpty{}, in: formSource{\"createTime\": []string{\" \"}}},\n\t\t{need: &needFixUnixNanoEmpty{}, got: &needFixUnixNanoEmpty{}, in: formSource{\"createTime\": []string{}}},\n\t}\n\n\tfor _, v := range tests {\n\t\terr := mapForm(v.got, v.in)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, v.need, v.got)\n\t}\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":237,"symbol":"needFixUnixNanoEmpty","kind":"type","lang":"go","code":"type needFixUnixNanoEmpty struct {\n\t\tCreateTime time.Time `form:\"createTime\" time_format:\"unixNano\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":254,"symbol":"TestMappingTimeDuration","kind":"function","lang":"go","code":"func TestMappingTimeDuration(t *testing.T) {\n\ttype needFixDurationEmpty struct {\n\t\tDuration time.Duration `form:\"duration\"`\n\t}\n\n\tvar s struct {\n\t\tD time.Duration\n\t}\n\n\t// ok\n\terr := mappingByPtr(&s, formSource{\"D\": {\"5s\"}}, \"form\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, 5*time.Second, s.D)\n\n\t// ok\n\ttests := []bindTestData{\n\t\t{need: &needFixDurationEmpty{}, got: &needFixDurationEmpty{}, in: formSource{\"duration\": []string{\" \"}}},\n\t\t{need: &needFixDurationEmpty{}, got: &needFixDurationEmpty{}, in: formSource{\"duration\": []string{}}},\n\t}\n\n\tfor _, v := range tests {\n\t\terr := mapForm(v.got, v.in)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, v.need, v.got)\n\t}\n\t// error\n\terr = mappingByPtr(&s, formSource{\"D\": {\"wrong\"}}, \"form\")\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":255,"symbol":"needFixDurationEmpty","kind":"type","lang":"go","code":"type needFixDurationEmpty struct {\n\t\tDuration time.Duration `form:\"duration\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":259,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tD time.Duration\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":284,"symbol":"TestMappingSlice","kind":"function","lang":"go","code":"func TestMappingSlice(t *testing.T) {\n\tvar s struct {\n\t\tSlice []int `form:\"slice,default=9\"`\n\t}\n\n\t// default value\n\terr := mappingByPtr(&s, formSource{}, \"form\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, []int{9}, s.Slice)\n\n\t// ok\n\terr = mappingByPtr(&s, formSource{\"slice\": {\"3\", \"4\"}}, \"form\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, []int{3, 4}, s.Slice)\n\n\t// error\n\terr = mappingByPtr(&s, formSource{\"slice\": {\"wrong\"}}, \"form\")\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":285,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tSlice []int `form:\"slice,default=9\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":304,"symbol":"TestMappingArray","kind":"function","lang":"go","code":"func TestMappingArray(t *testing.T) {\n\tvar s struct {\n\t\tArray [2]int `form:\"array,default=9\"`\n\t}\n\n\t// wrong default\n\terr := mappingByPtr(&s, formSource{}, \"form\")\n\trequire.Error(t, err)\n\n\t// ok\n\terr = mappingByPtr(&s, formSource{\"array\": {\"3\", \"4\"}}, \"form\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, [2]int{3, 4}, s.Array)\n\n\t// error - not enough vals\n\terr = mappingByPtr(&s, formSource{\"array\": {\"3\"}}, \"form\")\n\trequire.Error(t, err)\n\n\t// error - wrong value\n\terr = mappingByPtr(&s, formSource{\"array\": {\"wrong\"}}, \"form\")\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":305,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tArray [2]int `form:\"array,default=9\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":327,"symbol":"TestMappingCollectionFormat","kind":"function","lang":"go","code":"func TestMappingCollectionFormat(t *testing.T) {\n\tvar s struct {\n\t\tSliceMulti []int `form:\"slice_multi\" collection_format:\"multi\"`\n\t\tSliceCsv []int `form:\"slice_csv\" collection_format:\"csv\"`\n\t\tSliceSsv []int `form:\"slice_ssv\" collection_format:\"ssv\"`\n\t\tSliceTsv []int `form:\"slice_tsv\" collection_format:\"tsv\"`\n\t\tSlicePipes []int `form:\"slice_pipes\" collection_format:\"pipes\"`\n\t\tArrayMulti [2]int `form:\"array_multi\" collection_format:\"multi\"`\n\t\tArrayCsv [2]int `form:\"array_csv\" collection_format:\"csv\"`\n\t\tArraySsv [2]int `form:\"array_ssv\" collection_format:\"ssv\"`\n\t\tArrayTsv [2]int `form:\"array_tsv\" collection_format:\"tsv\"`\n\t\tArrayPipes [2]int `form:\"array_pipes\" collection_format:\"pipes\"`\n\t}\n\terr := mappingByPtr(&s, formSource{\n\t\t\"slice_multi\": {\"1\", \"2\"},\n\t\t\"slice_csv\": {\"1,2\"},\n\t\t\"slice_ssv\": {\"1 2\"},\n\t\t\"slice_tsv\": {\"1\t2\"},\n\t\t\"slice_pipes\": {\"1|2\"},\n\t\t\"array_multi\": {\"1\", \"2\"},\n\t\t\"array_csv\": {\"1,2\"},\n\t\t\"array_ssv\": {\"1 2\"},\n\t\t\"array_tsv\": {\"1\t2\"},\n\t\t\"array_pipes\": {\"1|2\"},\n\t}, \"form\")\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, []int{1, 2}, s.SliceMulti)\n\tassert.Equal(t, []int{1, 2}, s.SliceCsv)\n\tassert.Equal(t, []int{1, 2}, s.SliceSsv)\n\tassert.Equal(t, "} {"repo":"gin","file":"binding/form_mapping_test.go","line":328,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tSliceMulti []int `form:\"slice_multi\" collection_format:\"multi\"`\n\t\tSliceCsv []int `form:\"slice_csv\" collection_format:\"csv\"`\n\t\tSliceSsv []int `form:\"slice_ssv\" collection_format:\"ssv\"`\n\t\tSliceTsv []int `form:\"slice_tsv\" collection_format:\"tsv\"`\n\t\tSlicePipes []int `form:\"slice_pipes\" collection_format:\"pipes\"`\n\t\tArrayMulti [2]int `form:\"array_multi\" collection_format:\"multi\"`\n\t\tArrayCsv [2]int `form:\"array_csv\" collection_format:\"csv\"`\n\t\tArraySsv [2]int `form:\"array_ssv\" collection_format:\"ssv\"`\n\t\tArrayTsv [2]int `form:\"array_tsv\" collection_format:\"tsv\"`\n\t\tArrayPipes [2]int `form:\"array_pipes\" collection_format:\"pipes\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":366,"symbol":"TestMappingCollectionFormatInvalid","kind":"function","lang":"go","code":"func TestMappingCollectionFormatInvalid(t *testing.T) {\n\tvar s struct {\n\t\tSliceCsv []int `form:\"slice_csv\" collection_format:\"xxx\"`\n\t}\n\terr := mappingByPtr(&s, formSource{\n\t\t\"slice_csv\": {\"1,2\"},\n\t}, \"form\")\n\trequire.Error(t, err)\n\n\tvar s2 struct {\n\t\tArrayCsv [2]int `form:\"array_csv\" collection_format:\"xxx\"`\n\t}\n\terr = mappingByPtr(&s2, formSource{\n\t\t\"array_csv\": {\"1,2\"},\n\t}, \"form\")\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":367,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tSliceCsv []int `form:\"slice_csv\" collection_format:\"xxx\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":375,"symbol":"s2","kind":"variable","lang":"go","code":"s2 struct {\n\t\tArrayCsv [2]int `form:\"array_csv\" collection_format:\"xxx\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":384,"symbol":"TestMappingMultipleDefaultWithCollectionFormat","kind":"function","lang":"go","code":"func TestMappingMultipleDefaultWithCollectionFormat(t *testing.T) {\n\tvar s struct {\n\t\tSliceMulti []int `form:\",default=1;2;3\" collection_format:\"multi\"`\n\t\tSliceCsv []int `form:\",default=1;2;3\" collection_format:\"csv\"`\n\t\tSliceSsv []int `form:\",default=1 2 3\" collection_format:\"ssv\"`\n\t\tSliceTsv []int `form:\",default=1\\t2\\t3\" collection_format:\"tsv\"`\n\t\tSlicePipes []int `form:\",default=1|2|3\" collection_format:\"pipes\"`\n\t\tArrayMulti [2]int `form:\",default=1;2\" collection_format:\"multi\"`\n\t\tArrayCsv [2]int `form:\",default=1;2\" collection_format:\"csv\"`\n\t\tArraySsv [2]int `form:\",default=1 2\" collection_format:\"ssv\"`\n\t\tArrayTsv [2]int `form:\",default=1\\t2\" collection_format:\"tsv\"`\n\t\tArrayPipes [2]int `form:\",default=1|2\" collection_format:\"pipes\"`\n\t\tSliceStringMulti []string `form:\",default=1;2;3\" collection_format:\"multi\"`\n\t\tSliceStringCsv []string `form:\",default=1;2;3\" collection_format:\"csv\"`\n\t\tSliceStringSsv []string `form:\",default=1 2 3\" collection_format:\"ssv\"`\n\t\tSliceStringTsv []string `form:\",default=1\\t2\\t3\" collection_format:\"tsv\"`\n\t\tSliceStringPipes []string `for"} {"repo":"gin","file":"binding/form_mapping_test.go","line":385,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tSliceMulti []int `form:\",default=1;2;3\" collection_format:\"multi\"`\n\t\tSliceCsv []int `form:\",default=1;2;3\" collection_format:\"csv\"`\n\t\tSliceSsv []int `form:\",default=1 2 3\" collection_format:\"ssv\"`\n\t\tSliceTsv []int `form:\",default=1\\t2\\t3\" collection_format:\"tsv\"`\n\t\tSlicePipes []int `form:\",default=1|2|3\" collection_format:\"pipes\"`\n\t\tArrayMulti [2]int `form:\",default=1;2\" collection_format:\"multi\"`\n\t\tArrayCsv [2]int `form:\",default=1;2\" collection_format:\"csv\"`\n\t\tArraySsv [2]int `form:\",default=1 2\" collection_format:\"ssv\"`\n\t\tArrayTsv [2]int `form:\",default=1\\t2\" collection_format:\"tsv\"`\n\t\tArrayPipes [2]int `form:\",default=1|2\" collection_format:\"pipes\"`\n\t\tSliceStringMulti []string `form:\",default=1;2;3\" collection_format:\"multi\"`\n\t\tSliceStringCsv []string `form:\",default=1;2;3\" collection_format:\"csv\"`\n\t\tSliceStringSsv []string `form:\",default=1 2 3\" collection_format:\"ssv\"`\n\t\tSliceStringTsv []string `form:\",default=1\\t2\\t3\" collection_format:\"tsv\"`\n\t\tSliceStringPipes []string `form:\",default=1|2|3\" collection_format:\"pipes\"`\n\t\tArrayStringMulti [2]strin"} {"repo":"gin","file":"binding/form_mapping_test.go","line":432,"symbol":"TestMappingStructField","kind":"function","lang":"go","code":"func TestMappingStructField(t *testing.T) {\n\tvar s struct {\n\t\tJ struct {\n\t\t\tI int\n\t\t}\n\t}\n\n\terr := mappingByPtr(&s, formSource{\"J\": {`{\"I\": 9}`}}, \"form\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, 9, s.J.I)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":433,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tJ struct {\n\t\t\tI int\n\t\t}\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":444,"symbol":"TestMappingPtrField","kind":"function","lang":"go","code":"func TestMappingPtrField(t *testing.T) {\n\ttype ptrStruct struct {\n\t\tKey int64 `json:\"key\"`\n\t}\n\n\ttype ptrRequest struct {\n\t\tItems []*ptrStruct `json:\"items\" form:\"items\"`\n\t}\n\n\tvar err error\n\n\t// With 0 items.\n\tvar req0 ptrRequest\n\terr = mappingByPtr(&req0, formSource{}, \"form\")\n\trequire.NoError(t, err)\n\tassert.Empty(t, req0.Items)\n\n\t// With 1 item.\n\tvar req1 ptrRequest\n\terr = mappingByPtr(&req1, formSource{\"items\": {`{\"key\": 1}`}}, \"form\")\n\trequire.NoError(t, err)\n\tassert.Len(t, req1.Items, 1)\n\tassert.EqualValues(t, 1, req1.Items[0].Key)\n\n\t// With 2 items.\n\tvar req2 ptrRequest\n\terr = mappingByPtr(&req2, formSource{\"items\": {`{\"key\": 1}`, `{\"key\": 2}`}}, \"form\")\n\trequire.NoError(t, err)\n\tassert.Len(t, req2.Items, 2)\n\tassert.EqualValues(t, 1, req2.Items[0].Key)\n\tassert.EqualValues(t, 2, req2.Items[1].Key)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":445,"symbol":"ptrStruct","kind":"type","lang":"go","code":"type ptrStruct struct {\n\t\tKey int64 `json:\"key\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":449,"symbol":"ptrRequest","kind":"type","lang":"go","code":"type ptrRequest struct {\n\t\tItems []*ptrStruct `json:\"items\" form:\"items\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":453,"symbol":"err","kind":"variable","lang":"go","code":"err error"} {"repo":"gin","file":"binding/form_mapping_test.go","line":456,"symbol":"req0","kind":"variable","lang":"go","doc":"With 0 items.","code":"req0 ptrRequest"} {"repo":"gin","file":"binding/form_mapping_test.go","line":462,"symbol":"req1","kind":"variable","lang":"go","doc":"With 1 item.","code":"req1 ptrRequest"} {"repo":"gin","file":"binding/form_mapping_test.go","line":469,"symbol":"req2","kind":"variable","lang":"go","doc":"With 2 items.","code":"req2 ptrRequest"} {"repo":"gin","file":"binding/form_mapping_test.go","line":477,"symbol":"TestMappingMapField","kind":"function","lang":"go","code":"func TestMappingMapField(t *testing.T) {\n\tvar s struct {\n\t\tM map[string]int\n\t}\n\n\terr := mappingByPtr(&s, formSource{\"M\": {`{\"one\": 1}`}}, \"form\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]int{\"one\": 1}, s.M)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":478,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tM map[string]int\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":487,"symbol":"TestMappingIgnoredCircularRef","kind":"function","lang":"go","code":"func TestMappingIgnoredCircularRef(t *testing.T) {\n\ttype S struct {\n\t\tS *S `form:\"-\"`\n\t}\n\tvar s S\n\n\terr := mappingByPtr(&s, formSource{}, \"form\")\n\trequire.NoError(t, err)\n}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":488,"symbol":"S","kind":"type","lang":"go","code":"type S struct {\n\t\tS *S `form:\"-\"`\n\t}"} {"repo":"gin","file":"binding/form_mapping_test.go","line":491,"symbol":"s","kind":"variable","lang":"go","code":"s S"} {"repo":"gin","file":"binding/form_mapping_test.go","line":497,"symbol":"customUnmarshalParamHex","kind":"type","lang":"go","code":"type customUnmarshalParamHex int"} {"repo":"gin","file":"binding/header.go","line":13,"symbol":"headerBinding","kind":"type","lang":"go","code":"type headerBinding struct{}"} {"repo":"gin","file":"binding/header.go","line":15,"symbol":"Name","kind":"method","lang":"go","code":"func (headerBinding) Name() string {\n\treturn \"header\"\n}"} {"repo":"gin","file":"binding/header.go","line":19,"symbol":"Bind","kind":"method","lang":"go","code":"func (headerBinding) Bind(req *http.Request, obj any) error {\n\tif err := mapHeader(obj, req.Header); err != nil {\n\t\treturn err\n\t}\n\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/header.go","line":27,"symbol":"mapHeader","kind":"function","lang":"go","code":"func mapHeader(ptr any, h map[string][]string) error {\n\treturn mappingByPtr(ptr, headerSource(h), \"header\")\n}"} {"repo":"gin","file":"binding/header.go","line":31,"symbol":"headerSource","kind":"type","lang":"go","code":"type headerSource map[string][]string"} {"repo":"gin","file":"binding/header.go","line":33,"symbol":"_","kind":"variable","lang":"go","code":"_ setter = headerSource(nil)"} {"repo":"gin","file":"binding/header.go","line":35,"symbol":"TrySet","kind":"method","lang":"go","code":"func (hs headerSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (bool, error) {\n\treturn setByForm(value, field, hs, textproto.CanonicalMIMEHeaderKey(tagValue), opt)\n}"} {"repo":"gin","file":"binding/json.go","line":19,"symbol":"EnableDecoderUseNumber","kind":"variable","lang":"go","doc":"EnableDecoderUseNumber is used to call the UseNumber method on the JSON Decoder instance. UseNumber causes the Decoder to unmarshal a number into an any as a Number instead of as a float64.","code":"EnableDecoderUseNumber = false"} {"repo":"gin","file":"binding/json.go","line":25,"symbol":"EnableDecoderDisallowUnknownFields","kind":"variable","lang":"go","doc":"EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.","code":"EnableDecoderDisallowUnknownFields = false"} {"repo":"gin","file":"binding/json.go","line":27,"symbol":"jsonBinding","kind":"type","lang":"go","code":"type jsonBinding struct{}"} {"repo":"gin","file":"binding/json.go","line":29,"symbol":"Name","kind":"method","lang":"go","code":"func (jsonBinding) Name() string {\n\treturn \"json\"\n}"} {"repo":"gin","file":"binding/json.go","line":33,"symbol":"Bind","kind":"method","lang":"go","code":"func (jsonBinding) Bind(req *http.Request, obj any) error {\n\tif req == nil || req.Body == nil {\n\t\treturn errors.New(\"invalid request\")\n\t}\n\treturn decodeJSON(req.Body, obj)\n}"} {"repo":"gin","file":"binding/json.go","line":40,"symbol":"BindBody","kind":"method","lang":"go","code":"func (jsonBinding) BindBody(body []byte, obj any) error {\n\treturn decodeJSON(bytes.NewReader(body), obj)\n}"} {"repo":"gin","file":"binding/json.go","line":44,"symbol":"decodeJSON","kind":"function","lang":"go","code":"func decodeJSON(r io.Reader, obj any) error {\n\tdecoder := json.API.NewDecoder(r)\n\tif EnableDecoderUseNumber {\n\t\tdecoder.UseNumber()\n\t}\n\tif EnableDecoderDisallowUnknownFields {\n\t\tdecoder.DisallowUnknownFields()\n\t}\n\tif err := decoder.Decode(obj); err != nil {\n\t\treturn err\n\t}\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/json_test.go","line":22,"symbol":"TestJSONBindingBindBody","kind":"function","lang":"go","code":"func TestJSONBindingBindBody(t *testing.T) {\n\tvar s struct {\n\t\tFoo string `json:\"foo\"`\n\t}\n\terr := jsonBinding{}.BindBody([]byte(`{\"foo\": \"FOO\"}`), &s)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"FOO\", s.Foo)\n}"} {"repo":"gin","file":"binding/json_test.go","line":23,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tFoo string `json:\"foo\"`\n\t}"} {"repo":"gin","file":"binding/json_test.go","line":31,"symbol":"TestJSONBindingBindBodyMap","kind":"function","lang":"go","code":"func TestJSONBindingBindBodyMap(t *testing.T) {\n\ts := make(map[string]string)\n\terr := jsonBinding{}.BindBody([]byte(`{\"foo\": \"FOO\",\"hello\":\"world\"}`), &s)\n\trequire.NoError(t, err)\n\tassert.Len(t, s, 2)\n\tassert.Equal(t, \"FOO\", s[\"foo\"])\n\tassert.Equal(t, \"world\", s[\"hello\"])\n}"} {"repo":"gin","file":"binding/json_test.go","line":40,"symbol":"TestCustomJsonCodec","kind":"function","lang":"go","code":"func TestCustomJsonCodec(t *testing.T) {\n\t// Restore json encoding configuration after testing\n\toldMarshal := json.API\n\tdefer func() {\n\t\tjson.API = oldMarshal\n\t}()\n\t// Custom json api\n\tjson.API = customJsonApi{}\n\n\t// test decode json\n\tobj := customReq{}\n\terr := jsonBinding{}.BindBody([]byte(`{\"time_empty\":null,\"time_struct\": \"2001-12-05 10:01:02.345\",\"time_nil\":null,\"time_pointer\":\"2002-12-05 10:01:02.345\"}`), &obj)\n\trequire.NoError(t, err)\n\tassert.Equal(t, zeroTime, obj.TimeEmpty)\n\tassert.Equal(t, time.Date(2001, 12, 5, 10, 1, 2, 345000000, time.Local), obj.TimeStruct)\n\tassert.Nil(t, obj.TimeNil)\n\tassert.Equal(t, time.Date(2002, 12, 5, 10, 1, 2, 345000000, time.Local), *obj.TimePointer)\n\t// test encode json\n\tw := httptest.NewRecorder()\n\terr2 := (render.PureJSON{Data: obj}).Render(w)\n\trequire.NoError(t, err2)\n\tassert.JSONEq(t, \"{\\\"time_empty\\\":null,\\\"time_struct\\\":\\\"2001-12-05 10:01:02.345\\\",\\\"time_nil\\\":null,\\\"time_pointer\\\":\\\"2002-12-05 10:01:02.345\\\"}\\n\", w.Body.String())\n\tassert.Equal(t, \"application/json; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"binding/json_test.go","line":65,"symbol":"customReq","kind":"type","lang":"go","code":"type customReq struct {\n\tTimeEmpty time.Time `json:\"time_empty\"`\n\tTimeStruct time.Time `json:\"time_struct\"`\n\tTimeNil *time.Time `json:\"time_nil\"`\n\tTimePointer *time.Time `json:\"time_pointer\"`\n}"} {"repo":"gin","file":"binding/json_test.go","line":72,"symbol":"customConfig","kind":"variable","lang":"go","code":"customConfig = jsoniter.Config{\n\tEscapeHTML: true,\n\tSortMapKeys: true,\n\tValidateJsonRawMessage: true,\n}.Froze()"} {"repo":"gin","file":"binding/json_test.go","line":78,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tcustomConfig.RegisterExtension(&TimeEx{})\n\tcustomConfig.RegisterExtension(&TimePointerEx{})\n}"} {"repo":"gin","file":"binding/json_test.go","line":83,"symbol":"customJsonApi","kind":"type","lang":"go","code":"type customJsonApi struct{}"} {"repo":"gin","file":"binding/json_test.go","line":85,"symbol":"Marshal","kind":"method","lang":"go","code":"func (j customJsonApi) Marshal(v any) ([]byte, error) {\n\treturn customConfig.Marshal(v)\n}"} {"repo":"gin","file":"binding/json_test.go","line":89,"symbol":"Unmarshal","kind":"method","lang":"go","code":"func (j customJsonApi) Unmarshal(data []byte, v any) error {\n\treturn customConfig.Unmarshal(data, v)\n}"} {"repo":"gin","file":"binding/json_test.go","line":93,"symbol":"MarshalIndent","kind":"method","lang":"go","code":"func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {\n\treturn customConfig.MarshalIndent(v, prefix, indent)\n}"} {"repo":"gin","file":"binding/json_test.go","line":97,"symbol":"NewEncoder","kind":"method","lang":"go","code":"func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {\n\treturn customConfig.NewEncoder(writer)\n}"} {"repo":"gin","file":"binding/json_test.go","line":101,"symbol":"NewDecoder","kind":"method","lang":"go","code":"func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {\n\treturn customConfig.NewDecoder(reader)\n}"} {"repo":"gin","file":"binding/json_test.go","line":108,"symbol":"zeroTime","kind":"variable","lang":"go","code":"zeroTime = time.Time{}"} {"repo":"gin","file":"binding/json_test.go","line":109,"symbol":"timeType","kind":"variable","lang":"go","code":"timeType = reflect2.TypeOfPtr((*time.Time)(nil)).Elem()"} {"repo":"gin","file":"binding/json_test.go","line":110,"symbol":"defaultTimeCodec","kind":"variable","lang":"go","code":"defaultTimeCodec = &timeCodec{}"} {"repo":"gin","file":"binding/json_test.go","line":113,"symbol":"TimeEx","kind":"type","lang":"go","code":"type TimeEx struct {\n\tjsoniter.DummyExtension\n}"} {"repo":"gin","file":"binding/json_test.go","line":117,"symbol":"CreateDecoder","kind":"method","lang":"go","code":"func (te *TimeEx) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {\n\tif typ == timeType {\n\t\treturn defaultTimeCodec\n\t}\n\treturn nil\n}"} {"repo":"gin","file":"binding/json_test.go","line":124,"symbol":"CreateEncoder","kind":"method","lang":"go","code":"func (te *TimeEx) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {\n\tif typ == timeType {\n\t\treturn defaultTimeCodec\n\t}\n\treturn nil\n}"} {"repo":"gin","file":"binding/json_test.go","line":131,"symbol":"timeCodec","kind":"type","lang":"go","code":"type timeCodec struct{}"} {"repo":"gin","file":"binding/json_test.go","line":133,"symbol":"IsEmpty","kind":"method","lang":"go","code":"func (tc timeCodec) IsEmpty(ptr unsafe.Pointer) bool {\n\tt := *((*time.Time)(ptr))\n\treturn t.Equal(zeroTime)\n}"} {"repo":"gin","file":"binding/json_test.go","line":138,"symbol":"Encode","kind":"method","lang":"go","code":"func (tc timeCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {\n\tt := *((*time.Time)(ptr))\n\tif t.Equal(zeroTime) {\n\t\tstream.WriteNil()\n\t\treturn\n\t}\n\tstream.WriteString(t.In(time.Local).Format(\"2006-01-02 15:04:05.000\"))\n}"} {"repo":"gin","file":"binding/json_test.go","line":147,"symbol":"Decode","kind":"method","lang":"go","code":"func (tc timeCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {\n\tts := iter.ReadString()\n\tif len(ts) == 0 {\n\t\t*((*time.Time)(ptr)) = zeroTime\n\t\treturn\n\t}\n\tt, err := time.ParseInLocation(\"2006-01-02 15:04:05.000\", ts, time.Local)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t*((*time.Time)(ptr)) = t\n}"} {"repo":"gin","file":"binding/json_test.go","line":165,"symbol":"timePointerType","kind":"variable","lang":"go","code":"timePointerType = reflect2.TypeOfPtr((**time.Time)(nil)).Elem()"} {"repo":"gin","file":"binding/json_test.go","line":166,"symbol":"defaultTimePointerCodec","kind":"variable","lang":"go","code":"defaultTimePointerCodec = &timePointerCodec{}"} {"repo":"gin","file":"binding/json_test.go","line":169,"symbol":"TimePointerEx","kind":"type","lang":"go","code":"type TimePointerEx struct {\n\tjsoniter.DummyExtension\n}"} {"repo":"gin","file":"binding/json_test.go","line":173,"symbol":"CreateDecoder","kind":"method","lang":"go","code":"func (tpe *TimePointerEx) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {\n\tif typ == timePointerType {\n\t\treturn defaultTimePointerCodec\n\t}\n\treturn nil\n}"} {"repo":"gin","file":"binding/json_test.go","line":180,"symbol":"CreateEncoder","kind":"method","lang":"go","code":"func (tpe *TimePointerEx) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder {\n\tif typ == timePointerType {\n\t\treturn defaultTimePointerCodec\n\t}\n\treturn nil\n}"} {"repo":"gin","file":"binding/json_test.go","line":187,"symbol":"timePointerCodec","kind":"type","lang":"go","code":"type timePointerCodec struct{}"} {"repo":"gin","file":"binding/json_test.go","line":189,"symbol":"IsEmpty","kind":"method","lang":"go","code":"func (tpc timePointerCodec) IsEmpty(ptr unsafe.Pointer) bool {\n\tt := *((**time.Time)(ptr))\n\treturn t == nil || (*t).Equal(zeroTime)\n}"} {"repo":"gin","file":"binding/json_test.go","line":194,"symbol":"Encode","kind":"method","lang":"go","code":"func (tpc timePointerCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {\n\tt := *((**time.Time)(ptr))\n\tif t == nil || (*t).Equal(zeroTime) {\n\t\tstream.WriteNil()\n\t\treturn\n\t}\n\tstream.WriteString(t.In(time.Local).Format(\"2006-01-02 15:04:05.000\"))\n}"} {"repo":"gin","file":"binding/json_test.go","line":203,"symbol":"Decode","kind":"method","lang":"go","code":"func (tpc timePointerCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {\n\tts := iter.ReadString()\n\tif len(ts) == 0 {\n\t\t*((**time.Time)(ptr)) = nil\n\t\treturn\n\t}\n\tt, err := time.ParseInLocation(\"2006-01-02 15:04:05.000\", ts, time.Local)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t*((**time.Time)(ptr)) = &t\n}"} {"repo":"gin","file":"binding/msgpack.go","line":17,"symbol":"msgpackBinding","kind":"type","lang":"go","code":"type msgpackBinding struct{}"} {"repo":"gin","file":"binding/msgpack.go","line":19,"symbol":"Name","kind":"method","lang":"go","code":"func (msgpackBinding) Name() string {\n\treturn \"msgpack\"\n}"} {"repo":"gin","file":"binding/msgpack.go","line":23,"symbol":"Bind","kind":"method","lang":"go","code":"func (msgpackBinding) Bind(req *http.Request, obj any) error {\n\treturn decodeMsgPack(req.Body, obj)\n}"} {"repo":"gin","file":"binding/msgpack.go","line":27,"symbol":"BindBody","kind":"method","lang":"go","code":"func (msgpackBinding) BindBody(body []byte, obj any) error {\n\treturn decodeMsgPack(bytes.NewReader(body), obj)\n}"} {"repo":"gin","file":"binding/msgpack.go","line":31,"symbol":"decodeMsgPack","kind":"function","lang":"go","code":"func decodeMsgPack(r io.Reader, obj any) error {\n\tcdc := new(codec.MsgpackHandle)\n\tif err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil {\n\t\treturn err\n\t}\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/msgpack_test.go","line":18,"symbol":"TestMsgpackBindingBindBody","kind":"function","lang":"go","code":"func TestMsgpackBindingBindBody(t *testing.T) {\n\ttype teststruct struct {\n\t\tFoo string `msgpack:\"foo\"`\n\t}\n\tvar s teststruct\n\terr := msgpackBinding{}.BindBody(msgpackBody(t, teststruct{\"FOO\"}), &s)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"FOO\", s.Foo)\n}"} {"repo":"gin","file":"binding/msgpack_test.go","line":19,"symbol":"teststruct","kind":"type","lang":"go","code":"type teststruct struct {\n\t\tFoo string `msgpack:\"foo\"`\n\t}"} {"repo":"gin","file":"binding/msgpack_test.go","line":22,"symbol":"s","kind":"variable","lang":"go","code":"s teststruct"} {"repo":"gin","file":"binding/msgpack_test.go","line":28,"symbol":"msgpackBody","kind":"function","lang":"go","code":"func msgpackBody(t *testing.T, obj any) []byte {\n\tvar bs bytes.Buffer\n\th := &codec.MsgpackHandle{}\n\terr := codec.NewEncoder(&bs, h).Encode(obj)\n\trequire.NoError(t, err)\n\treturn bs.Bytes()\n}"} {"repo":"gin","file":"binding/msgpack_test.go","line":29,"symbol":"bs","kind":"variable","lang":"go","code":"bs bytes.Buffer"} {"repo":"gin","file":"binding/multipart_form_mapping.go","line":14,"symbol":"multipartRequest","kind":"type","lang":"go","code":"type multipartRequest http.Request"} {"repo":"gin","file":"binding/multipart_form_mapping.go","line":16,"symbol":"_","kind":"variable","lang":"go","code":"_ setter = (*multipartRequest)(nil)"} {"repo":"gin","file":"binding/multipart_form_mapping.go","line":20,"symbol":"ErrMultiFileHeader","kind":"variable","lang":"go","doc":"ErrMultiFileHeader multipart.FileHeader invalid","code":"ErrMultiFileHeader = errors.New(\"unsupported field type for multipart.FileHeader\")"} {"repo":"gin","file":"binding/multipart_form_mapping.go","line":23,"symbol":"ErrMultiFileHeaderLenInvalid","kind":"variable","lang":"go","doc":"ErrMultiFileHeaderLenInvalid array for []*multipart.FileHeader len invalid","code":"ErrMultiFileHeaderLenInvalid = errors.New(\"unsupported len of array for []*multipart.FileHeader\")"} {"repo":"gin","file":"binding/multipart_form_mapping.go","line":27,"symbol":"TrySet","kind":"method","lang":"go","doc":"TrySet tries to set a value by the multipart request with the binding a form file","code":"func (r *multipartRequest) TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (bool, error) {\n\tif files := r.MultipartForm.File[key]; len(files) != 0 {\n\t\treturn setByMultipartFormFile(value, field, files)\n\t}\n\n\treturn setByForm(value, field, r.MultipartForm.Value, key, opt)\n}"} {"repo":"gin","file":"binding/multipart_form_mapping.go","line":35,"symbol":"setByMultipartFormFile","kind":"function","lang":"go","code":"func setByMultipartFormFile(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSet bool, err error) {\n\tswitch value.Kind() {\n\tcase reflect.Ptr:\n\t\tswitch value.Interface().(type) {\n\t\tcase *multipart.FileHeader:\n\t\t\tvalue.Set(reflect.ValueOf(files[0]))\n\t\t\treturn true, nil\n\t\t}\n\tcase reflect.Struct:\n\t\tswitch value.Interface().(type) {\n\t\tcase multipart.FileHeader:\n\t\t\tvalue.Set(reflect.ValueOf(*files[0]))\n\t\t\treturn true, nil\n\t\t}\n\tcase reflect.Slice:\n\t\tslice := reflect.MakeSlice(value.Type(), len(files), len(files))\n\t\tisSet, err = setArrayOfMultipartFormFiles(slice, field, files)\n\t\tif err != nil || !isSet {\n\t\t\treturn isSet, err\n\t\t}\n\t\tvalue.Set(slice)\n\t\treturn true, nil\n\tcase reflect.Array:\n\t\treturn setArrayOfMultipartFormFiles(value, field, files)\n\t}\n\treturn false, ErrMultiFileHeader\n}"} {"repo":"gin","file":"binding/multipart_form_mapping.go","line":63,"symbol":"setArrayOfMultipartFormFiles","kind":"function","lang":"go","code":"func setArrayOfMultipartFormFiles(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSet bool, err error) {\n\tif value.Len() != len(files) {\n\t\treturn false, ErrMultiFileHeaderLenInvalid\n\t}\n\tfor i := range files {\n\t\tset, err := setByMultipartFormFile(value.Index(i), field, files[i:i+1])\n\t\tif err != nil || !set {\n\t\t\treturn set, err\n\t\t}\n\t}\n\treturn true, nil\n}"} {"repo":"gin","file":"binding/multipart_form_mapping_test.go","line":18,"symbol":"TestFormMultipartBindingBindOneFile","kind":"function","lang":"go","code":"func TestFormMultipartBindingBindOneFile(t *testing.T) {\n\tvar s struct {\n\t\tFileValue multipart.FileHeader `form:\"file\"`\n\t\tFilePtr *multipart.FileHeader `form:\"file\"`\n\t\tSliceValues []multipart.FileHeader `form:\"file\"`\n\t\tSlicePtrs []*multipart.FileHeader `form:\"file\"`\n\t\tArrayValues [1]multipart.FileHeader `form:\"file\"`\n\t\tArrayPtrs [1]*multipart.FileHeader `form:\"file\"`\n\t}\n\tfile := testFile{\"file\", \"file1\", []byte(\"hello\")}\n\n\treq := createRequestMultipartFiles(t, file)\n\terr := FormMultipart.Bind(req, &s)\n\trequire.NoError(t, err)\n\n\tassertMultipartFileHeader(t, &s.FileValue, file)\n\tassertMultipartFileHeader(t, s.FilePtr, file)\n\tassert.Len(t, s.SliceValues, 1)\n\tassertMultipartFileHeader(t, &s.SliceValues[0], file)\n\tassert.Len(t, s.SlicePtrs, 1)\n\tassertMultipartFileHeader(t, s.SlicePtrs[0], file)\n\tassertMultipartFileHeader(t, &s.ArrayValues[0], file)\n\tassertMultipartFileHeader(t, s.ArrayPtrs[0], file)\n}"} {"repo":"gin","file":"binding/multipart_form_mapping_test.go","line":19,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tFileValue multipart.FileHeader `form:\"file\"`\n\t\tFilePtr *multipart.FileHeader `form:\"file\"`\n\t\tSliceValues []multipart.FileHeader `form:\"file\"`\n\t\tSlicePtrs []*multipart.FileHeader `form:\"file\"`\n\t\tArrayValues [1]multipart.FileHeader `form:\"file\"`\n\t\tArrayPtrs [1]*multipart.FileHeader `form:\"file\"`\n\t}"} {"repo":"gin","file":"binding/multipart_form_mapping_test.go","line":43,"symbol":"TestFormMultipartBindingBindTwoFiles","kind":"function","lang":"go","code":"func TestFormMultipartBindingBindTwoFiles(t *testing.T) {\n\tvar s struct {\n\t\tSliceValues []multipart.FileHeader `form:\"file\"`\n\t\tSlicePtrs []*multipart.FileHeader `form:\"file\"`\n\t\tArrayValues [2]multipart.FileHeader `form:\"file\"`\n\t\tArrayPtrs [2]*multipart.FileHeader `form:\"file\"`\n\t}\n\tfiles := []testFile{\n\t\t{\"file\", \"file1\", []byte(\"hello\")},\n\t\t{\"file\", \"file2\", []byte(\"world\")},\n\t}\n\n\treq := createRequestMultipartFiles(t, files...)\n\terr := FormMultipart.Bind(req, &s)\n\trequire.NoError(t, err)\n\n\tassert.Len(t, s.SliceValues, len(files))\n\tassert.Len(t, s.SlicePtrs, len(files))\n\tassert.Len(t, s.ArrayValues, len(files))\n\tassert.Len(t, s.ArrayPtrs, len(files))\n\n\tfor i, file := range files {\n\t\tassertMultipartFileHeader(t, &s.SliceValues[i], file)\n\t\tassertMultipartFileHeader(t, s.SlicePtrs[i], file)\n\t\tassertMultipartFileHeader(t, &s.ArrayValues[i], file)\n\t\tassertMultipartFileHeader(t, s.ArrayPtrs[i], file)\n\t}\n}"} {"repo":"gin","file":"binding/multipart_form_mapping_test.go","line":44,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tSliceValues []multipart.FileHeader `form:\"file\"`\n\t\tSlicePtrs []*multipart.FileHeader `form:\"file\"`\n\t\tArrayValues [2]multipart.FileHeader `form:\"file\"`\n\t\tArrayPtrs [2]*multipart.FileHeader `form:\"file\"`\n\t}"} {"repo":"gin","file":"binding/multipart_form_mapping_test.go","line":72,"symbol":"TestFormMultipartBindingBindError","kind":"function","lang":"go","code":"func TestFormMultipartBindingBindError(t *testing.T) {\n\tfiles := []testFile{\n\t\t{\"file\", \"file1\", []byte(\"hello\")},\n\t\t{\"file\", \"file2\", []byte(\"world\")},\n\t}\n\n\tfor _, tt := range []struct {\n\t\tname string\n\t\ts any\n\t}{\n\t\t{\"wrong type\", &struct {\n\t\t\tFiles int `form:\"file\"`\n\t\t}{}},\n\t\t{\"wrong array size\", &struct {\n\t\t\tFiles [1]*multipart.FileHeader `form:\"file\"`\n\t\t}{}},\n\t\t{\"wrong slice type\", &struct {\n\t\t\tFiles []int `form:\"file\"`\n\t\t}{}},\n\t} {\n\t\treq := createRequestMultipartFiles(t, files...)\n\t\terr := FormMultipart.Bind(req, tt.s)\n\t\trequire.Error(t, err)\n\t}\n}"} {"repo":"gin","file":"binding/multipart_form_mapping_test.go","line":98,"symbol":"testFile","kind":"type","lang":"go","code":"type testFile struct {\n\tFieldname string\n\tFilename string\n\tContent []byte\n}"} {"repo":"gin","file":"binding/multipart_form_mapping_test.go","line":104,"symbol":"createRequestMultipartFiles","kind":"function","lang":"go","code":"func createRequestMultipartFiles(t *testing.T, files ...testFile) *http.Request {\n\tvar body bytes.Buffer\n\n\tmw := multipart.NewWriter(&body)\n\tfor _, file := range files {\n\t\tfw, err := mw.CreateFormFile(file.Fieldname, file.Filename)\n\t\trequire.NoError(t, err)\n\n\t\tn, err := fw.Write(file.Content)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, len(file.Content), n)\n\t}\n\terr := mw.Close()\n\trequire.NoError(t, err)\n\n\treq, err := http.NewRequest(http.MethodPost, \"/\", &body)\n\trequire.NoError(t, err)\n\n\treq.Header.Set(\"Content-Type\", MIMEMultipartPOSTForm+\"; boundary=\"+mw.Boundary())\n\treturn req\n}"} {"repo":"gin","file":"binding/multipart_form_mapping_test.go","line":105,"symbol":"body","kind":"variable","lang":"go","code":"body bytes.Buffer"} {"repo":"gin","file":"binding/multipart_form_mapping_test.go","line":126,"symbol":"assertMultipartFileHeader","kind":"function","lang":"go","code":"func assertMultipartFileHeader(t *testing.T, fh *multipart.FileHeader, file testFile) {\n\tassert.Equal(t, file.Filename, fh.Filename)\n\tassert.Equal(t, int64(len(file.Content)), fh.Size)\n\n\tfl, err := fh.Open()\n\trequire.NoError(t, err)\n\n\tbody, err := io.ReadAll(fl)\n\trequire.NoError(t, err)\n\tassert.Equal(t, string(file.Content), string(body))\n\n\terr = fl.Close()\n\trequire.NoError(t, err)\n}"} {"repo":"gin","file":"binding/plain.go","line":12,"symbol":"plainBinding","kind":"type","lang":"go","code":"type plainBinding struct{}"} {"repo":"gin","file":"binding/plain.go","line":14,"symbol":"Name","kind":"method","lang":"go","code":"func (plainBinding) Name() string {\n\treturn \"plain\"\n}"} {"repo":"gin","file":"binding/plain.go","line":18,"symbol":"Bind","kind":"method","lang":"go","code":"func (plainBinding) Bind(req *http.Request, obj any) error {\n\tall, err := io.ReadAll(req.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn decodePlain(all, obj)\n}"} {"repo":"gin","file":"binding/plain.go","line":27,"symbol":"BindBody","kind":"method","lang":"go","code":"func (plainBinding) BindBody(body []byte, obj any) error {\n\treturn decodePlain(body, obj)\n}"} {"repo":"gin","file":"binding/plain.go","line":31,"symbol":"decodePlain","kind":"function","lang":"go","code":"func decodePlain(data []byte, obj any) error {\n\tif obj == nil {\n\t\treturn nil\n\t}\n\n\tv := reflect.ValueOf(obj)\n\n\tfor v.Kind() == reflect.Ptr {\n\t\tif v.IsNil() {\n\t\t\treturn nil\n\t\t}\n\t\tv = v.Elem()\n\t}\n\n\tif v.Kind() == reflect.String {\n\t\tv.SetString(bytesconv.BytesToString(data))\n\t\treturn nil\n\t}\n\n\tif _, ok := v.Interface().([]byte); ok {\n\t\tv.SetBytes(data)\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"type (%T) unknown type\", v)\n}"} {"repo":"gin","file":"binding/protobuf.go","line":15,"symbol":"protobufBinding","kind":"type","lang":"go","code":"type protobufBinding struct{}"} {"repo":"gin","file":"binding/protobuf.go","line":17,"symbol":"Name","kind":"method","lang":"go","code":"func (protobufBinding) Name() string {\n\treturn \"protobuf\"\n}"} {"repo":"gin","file":"binding/protobuf.go","line":21,"symbol":"Bind","kind":"method","lang":"go","code":"func (b protobufBinding) Bind(req *http.Request, obj any) error {\n\tbuf, err := io.ReadAll(req.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn b.BindBody(buf, obj)\n}"} {"repo":"gin","file":"binding/protobuf.go","line":29,"symbol":"BindBody","kind":"method","lang":"go","code":"func (protobufBinding) BindBody(body []byte, obj any) error {\n\tmsg, ok := obj.(proto.Message)\n\tif !ok {\n\t\treturn errors.New(\"obj is not ProtoMessage\")\n\t}\n\tif err := proto.Unmarshal(body, msg); err != nil {\n\t\treturn err\n\t}\n\t// Here it's same to return validate(obj), but until now we can't add\n\t// `binding:\"\"` to the struct which automatically generate by gen-proto\n\treturn nil\n\t// return validate(obj)\n}"} {"repo":"gin","file":"binding/query.go","line":9,"symbol":"queryBinding","kind":"type","lang":"go","code":"type queryBinding struct{}"} {"repo":"gin","file":"binding/query.go","line":11,"symbol":"Name","kind":"method","lang":"go","code":"func (queryBinding) Name() string {\n\treturn \"query\"\n}"} {"repo":"gin","file":"binding/query.go","line":15,"symbol":"Bind","kind":"method","lang":"go","code":"func (queryBinding) Bind(req *http.Request, obj any) error {\n\tvalues := req.URL.Query()\n\tif err := mapForm(obj, values); err != nil {\n\t\treturn err\n\t}\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/toml.go","line":15,"symbol":"tomlBinding","kind":"type","lang":"go","code":"type tomlBinding struct{}"} {"repo":"gin","file":"binding/toml.go","line":17,"symbol":"Name","kind":"method","lang":"go","code":"func (tomlBinding) Name() string {\n\treturn \"toml\"\n}"} {"repo":"gin","file":"binding/toml.go","line":21,"symbol":"Bind","kind":"method","lang":"go","code":"func (tomlBinding) Bind(req *http.Request, obj any) error {\n\treturn decodeToml(req.Body, obj)\n}"} {"repo":"gin","file":"binding/toml.go","line":25,"symbol":"BindBody","kind":"method","lang":"go","code":"func (tomlBinding) BindBody(body []byte, obj any) error {\n\treturn decodeToml(bytes.NewReader(body), obj)\n}"} {"repo":"gin","file":"binding/toml.go","line":29,"symbol":"decodeToml","kind":"function","lang":"go","code":"func decodeToml(r io.Reader, obj any) error {\n\tdecoder := toml.NewDecoder(r)\n\tif err := decoder.Decode(obj); err != nil {\n\t\treturn err\n\t}\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/toml_test.go","line":14,"symbol":"TestTOMLBindingBindBody","kind":"function","lang":"go","code":"func TestTOMLBindingBindBody(t *testing.T) {\n\tvar s struct {\n\t\tFoo string `toml:\"foo\"`\n\t}\n\ttomlBody := `foo=\"FOO\"`\n\terr := tomlBinding{}.BindBody([]byte(tomlBody), &s)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"FOO\", s.Foo)\n}"} {"repo":"gin","file":"binding/toml_test.go","line":15,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tFoo string `toml:\"foo\"`\n\t}"} {"repo":"gin","file":"binding/uri.go","line":7,"symbol":"uriBinding","kind":"type","lang":"go","code":"type uriBinding struct{}"} {"repo":"gin","file":"binding/uri.go","line":9,"symbol":"Name","kind":"method","lang":"go","code":"func (uriBinding) Name() string {\n\treturn \"uri\"\n}"} {"repo":"gin","file":"binding/uri.go","line":13,"symbol":"BindUri","kind":"method","lang":"go","code":"func (uriBinding) BindUri(m map[string][]string, obj any) error {\n\tif err := mapURI(obj, m); err != nil {\n\t\treturn err\n\t}\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/validate_test.go","line":17,"symbol":"testInterface","kind":"type","lang":"go","code":"type testInterface interface {\n\tString() string\n}"} {"repo":"gin","file":"binding/validate_test.go","line":21,"symbol":"substructNoValidation","kind":"type","lang":"go","code":"type substructNoValidation struct {\n\tIString string\n\tIInt int\n}"} {"repo":"gin","file":"binding/validate_test.go","line":26,"symbol":"mapNoValidationSub","kind":"type","lang":"go","code":"type mapNoValidationSub map[string]substructNoValidation"} {"repo":"gin","file":"binding/validate_test.go","line":28,"symbol":"structNoValidationValues","kind":"type","lang":"go","code":"type structNoValidationValues struct {\n\tsubstructNoValidation\n\n\tBoolean bool\n\n\tUinteger uint\n\tInteger int\n\tInteger8 int8\n\tInteger16 int16\n\tInteger32 int32\n\tInteger64 int64\n\tUinteger8 uint8\n\tUinteger16 uint16\n\tUinteger32 uint32\n\tUinteger64 uint64\n\n\tFloat32 float32\n\tFloat64 float64\n\n\tString string\n\n\tDate time.Time\n\n\tStruct substructNoValidation\n\tInlinedStruct struct {\n\t\tString []string\n\t\tInteger int\n\t}\n\n\tIntSlice []int\n\tIntPointerSlice []*int\n\tStructPointerSlice []*substructNoValidation\n\tStructSlice []substructNoValidation\n\tInterfaceSlice []testInterface\n\n\tUniversalInterface any\n\tCustomInterface testInterface\n\n\tFloatMap map[string]float32\n\tStructMap mapNoValidationSub\n}"} {"repo":"gin","file":"binding/validate_test.go","line":70,"symbol":"createNoValidationValues","kind":"function","lang":"go","code":"func createNoValidationValues() structNoValidationValues {\n\tinteger := 1\n\ts := structNoValidationValues{\n\t\tBoolean: true,\n\t\tUinteger: 1 << 29,\n\t\tInteger: -10000,\n\t\tInteger8: 120,\n\t\tInteger16: -20000,\n\t\tInteger32: 1 << 29,\n\t\tInteger64: 1 << 61,\n\t\tUinteger8: 250,\n\t\tUinteger16: 50000,\n\t\tUinteger32: 1 << 31,\n\t\tUinteger64: 1 << 62,\n\t\tFloat32: 123.456,\n\t\tFloat64: 123.456789,\n\t\tString: \"text\",\n\t\tDate: time.Time{},\n\t\tCustomInterface: &bytes.Buffer{},\n\t\tStruct: substructNoValidation{},\n\t\tIntSlice: []int{-3, -2, 1, 0, 1, 2, 3},\n\t\tIntPointerSlice: []*int{&integer},\n\t\tStructSlice: []substructNoValidation{},\n\t\tUniversalInterface: 1.2,\n\t\tFloatMap: map[string]float32{\n\t\t\t\"foo\": 1.23,\n\t\t\t\"bar\": 232.323,\n\t\t},\n\t\tStructMap: mapNoValidationSub{\n\t\t\t\"foo\": substructNoValidation{},\n\t\t\t\"bar\": substructNoValidation{},\n\t\t},\n\t\t// StructPointerSlice []noValidationSub\n\t\t// InterfaceSlice []testInterface\n\t}\n\ts.InlinedStruct.Integer = 1000\n\ts.InlinedStruct.String = []string{\"first\", \"second\"}\n\ts.IString = \"substring\"\n\ts.IInt ="} {"repo":"gin","file":"binding/validate_test.go","line":112,"symbol":"TestValidateNoValidationValues","kind":"function","lang":"go","code":"func TestValidateNoValidationValues(t *testing.T) {\n\torigin := createNoValidationValues()\n\ttest := createNoValidationValues()\n\tempty := structNoValidationValues{}\n\n\trequire.NoError(t, validate(test))\n\trequire.NoError(t, validate(&test))\n\trequire.NoError(t, validate(empty))\n\trequire.NoError(t, validate(&empty))\n\n\tassert.Equal(t, origin, test)\n}"} {"repo":"gin","file":"binding/validate_test.go","line":125,"symbol":"structNoValidationPointer","kind":"type","lang":"go","code":"type structNoValidationPointer struct {\n\tsubstructNoValidation\n\n\tBoolean bool\n\n\tUinteger *uint\n\tInteger *int\n\tInteger8 *int8\n\tInteger16 *int16\n\tInteger32 *int32\n\tInteger64 *int64\n\tUinteger8 *uint8\n\tUinteger16 *uint16\n\tUinteger32 *uint32\n\tUinteger64 *uint64\n\n\tFloat32 *float32\n\tFloat64 *float64\n\n\tString *string\n\n\tDate *time.Time\n\n\tStruct *substructNoValidation\n\n\tIntSlice *[]int\n\tIntPointerSlice *[]*int\n\tStructPointerSlice *[]*substructNoValidation\n\tStructSlice *[]substructNoValidation\n\tInterfaceSlice *[]testInterface\n\n\tFloatMap *map[string]float32\n\tStructMap *mapNoValidationSub\n}"} {"repo":"gin","file":"binding/validate_test.go","line":160,"symbol":"TestValidateNoValidationPointers","kind":"function","lang":"go","code":"func TestValidateNoValidationPointers(t *testing.T) {\n\t// origin := createNoValidation_values()\n\t// test := createNoValidation_values()\n\tempty := structNoValidationPointer{}\n\n\t// assert.Nil(t, validate(test))\n\t// assert.Nil(t, validate(&test))\n\trequire.NoError(t, validate(empty))\n\trequire.NoError(t, validate(&empty))\n\n\t// assert.Equal(t, origin, test)\n}"} {"repo":"gin","file":"binding/validate_test.go","line":173,"symbol":"Object","kind":"type","lang":"go","code":"type Object map[string]any"} {"repo":"gin","file":"binding/validate_test.go","line":175,"symbol":"TestValidatePrimitives","kind":"function","lang":"go","code":"func TestValidatePrimitives(t *testing.T) {\n\tobj := Object{\"foo\": \"bar\", \"bar\": 1}\n\trequire.NoError(t, validate(obj))\n\trequire.NoError(t, validate(&obj))\n\tassert.Equal(t, Object{\"foo\": \"bar\", \"bar\": 1}, obj)\n\n\tobj2 := []Object{{\"foo\": \"bar\", \"bar\": 1}, {\"foo\": \"bar\", \"bar\": 1}}\n\trequire.NoError(t, validate(obj2))\n\trequire.NoError(t, validate(&obj2))\n\n\tnu := 10\n\trequire.NoError(t, validate(nu))\n\trequire.NoError(t, validate(&nu))\n\tassert.Equal(t, 10, nu)\n\n\tstr := \"value\"\n\trequire.NoError(t, validate(str))\n\trequire.NoError(t, validate(&str))\n\tassert.Equal(t, \"value\", str)\n}"} {"repo":"gin","file":"binding/validate_test.go","line":196,"symbol":"structModifyValidation","kind":"type","lang":"go","code":"type structModifyValidation struct {\n\tInteger int\n}"} {"repo":"gin","file":"binding/validate_test.go","line":200,"symbol":"toZero","kind":"function","lang":"go","code":"func toZero(sl validator.StructLevel) {\n\ts := sl.Top().Interface().(*structModifyValidation)\n\ts.Integer = 0\n}"} {"repo":"gin","file":"binding/validate_test.go","line":205,"symbol":"TestValidateAndModifyStruct","kind":"function","lang":"go","code":"func TestValidateAndModifyStruct(t *testing.T) {\n\t// This validates that pointers to structs are passed to the validator\n\t// giving us the ability to modify the struct being validated.\n\tengine, ok := Validator.Engine().(*validator.Validate)\n\tassert.True(t, ok)\n\n\tengine.RegisterStructValidation(toZero, structModifyValidation{})\n\n\ts := structModifyValidation{Integer: 1}\n\terrs := validate(&s)\n\n\trequire.NoError(t, errs)\n\tassert.Equal(t, structModifyValidation{Integer: 0}, s)\n}"} {"repo":"gin","file":"binding/validate_test.go","line":223,"symbol":"structCustomValidation","kind":"type","lang":"go","doc":"structCustomValidation is a helper struct we use to check that custom validation can be registered on it. The `notone` binding directive is for custom validation and registered later.","code":"type structCustomValidation struct {\n\tInteger int `binding:\"notone\"`\n}"} {"repo":"gin","file":"binding/validate_test.go","line":227,"symbol":"notOne","kind":"function","lang":"go","code":"func notOne(f1 validator.FieldLevel) bool {\n\tif val, ok := f1.Field().Interface().(int); ok {\n\t\treturn val != 1\n\t}\n\treturn false\n}"} {"repo":"gin","file":"binding/validate_test.go","line":234,"symbol":"TestValidatorEngine","kind":"function","lang":"go","code":"func TestValidatorEngine(t *testing.T) {\n\t// This validates that the function `notOne` matches\n\t// the expected function signature by `defaultValidator`\n\t// and by extension the validator library.\n\tengine, ok := Validator.Engine().(*validator.Validate)\n\tassert.True(t, ok)\n\n\terr := engine.RegisterValidation(\"notone\", notOne)\n\t// Check that we can register custom validation without error\n\trequire.NoError(t, err)\n\n\t// Create an instance which will fail validation\n\twithOne := structCustomValidation{Integer: 1}\n\terrs := validate(withOne)\n\n\t// Check that we got back non-nil errs\n\trequire.Error(t, errs)\n\t// Check that the error matches expectation\n\trequire.Error(t, errs, \"notone\")\n}"} {"repo":"gin","file":"binding/xml.go","line":14,"symbol":"xmlBinding","kind":"type","lang":"go","code":"type xmlBinding struct{}"} {"repo":"gin","file":"binding/xml.go","line":16,"symbol":"Name","kind":"method","lang":"go","code":"func (xmlBinding) Name() string {\n\treturn \"xml\"\n}"} {"repo":"gin","file":"binding/xml.go","line":20,"symbol":"Bind","kind":"method","lang":"go","code":"func (xmlBinding) Bind(req *http.Request, obj any) error {\n\treturn decodeXML(req.Body, obj)\n}"} {"repo":"gin","file":"binding/xml.go","line":24,"symbol":"BindBody","kind":"method","lang":"go","code":"func (xmlBinding) BindBody(body []byte, obj any) error {\n\treturn decodeXML(bytes.NewReader(body), obj)\n}"} {"repo":"gin","file":"binding/xml.go","line":28,"symbol":"decodeXML","kind":"function","lang":"go","code":"func decodeXML(r io.Reader, obj any) error {\n\tdecoder := xml.NewDecoder(r)\n\tif err := decoder.Decode(obj); err != nil {\n\t\treturn err\n\t}\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/xml_test.go","line":14,"symbol":"TestXMLBindingBindBody","kind":"function","lang":"go","code":"func TestXMLBindingBindBody(t *testing.T) {\n\tvar s struct {\n\t\tFoo string `xml:\"foo\"`\n\t}\n\txmlBody := `\n\n FOO\n`\n\terr := xmlBinding{}.BindBody([]byte(xmlBody), &s)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"FOO\", s.Foo)\n}"} {"repo":"gin","file":"binding/xml_test.go","line":15,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tFoo string `xml:\"foo\"`\n\t}"} {"repo":"gin","file":"binding/yaml.go","line":15,"symbol":"yamlBinding","kind":"type","lang":"go","code":"type yamlBinding struct{}"} {"repo":"gin","file":"binding/yaml.go","line":17,"symbol":"Name","kind":"method","lang":"go","code":"func (yamlBinding) Name() string {\n\treturn \"yaml\"\n}"} {"repo":"gin","file":"binding/yaml.go","line":21,"symbol":"Bind","kind":"method","lang":"go","code":"func (yamlBinding) Bind(req *http.Request, obj any) error {\n\treturn decodeYAML(req.Body, obj)\n}"} {"repo":"gin","file":"binding/yaml.go","line":25,"symbol":"BindBody","kind":"method","lang":"go","code":"func (yamlBinding) BindBody(body []byte, obj any) error {\n\treturn decodeYAML(bytes.NewReader(body), obj)\n}"} {"repo":"gin","file":"binding/yaml.go","line":29,"symbol":"decodeYAML","kind":"function","lang":"go","code":"func decodeYAML(r io.Reader, obj any) error {\n\tdecoder := yaml.NewDecoder(r)\n\tif err := decoder.Decode(obj); err != nil {\n\t\treturn err\n\t}\n\treturn validate(obj)\n}"} {"repo":"gin","file":"binding/yaml_test.go","line":14,"symbol":"TestYAMLBindingBindBody","kind":"function","lang":"go","code":"func TestYAMLBindingBindBody(t *testing.T) {\n\tvar s struct {\n\t\tFoo string `yaml:\"foo\"`\n\t}\n\terr := yamlBinding{}.BindBody([]byte(\"foo: FOO\"), &s)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"FOO\", s.Foo)\n}"} {"repo":"gin","file":"binding/yaml_test.go","line":15,"symbol":"s","kind":"variable","lang":"go","code":"s struct {\n\t\tFoo string `yaml:\"foo\"`\n\t}"} {"repo":"gin","file":"codec/json/api.go","line":10,"symbol":"API","kind":"variable","lang":"go","doc":"API the json codec in use.","code":"API Core"} {"repo":"gin","file":"codec/json/api.go","line":13,"symbol":"Core","kind":"type","lang":"go","doc":"Core the api for json codec.","code":"type Core interface {\n\tMarshal(v any) ([]byte, error)\n\tUnmarshal(data []byte, v any) error\n\tMarshalIndent(v any, prefix, indent string) ([]byte, error)\n\tNewEncoder(writer io.Writer) Encoder\n\tNewDecoder(reader io.Reader) Decoder\n}"} {"repo":"gin","file":"codec/json/api.go","line":22,"symbol":"Encoder","kind":"type","lang":"go","doc":"Encoder an interface writes JSON values to an output stream.","code":"type Encoder interface {\n\t// SetEscapeHTML specifies whether problematic HTML characters\n\t// should be escaped inside JSON quoted strings.\n\t// The default behavior is to escape &, <, and > to \\u0026, \\u003c, and \\u003e\n\t// to avoid certain safety problems that can arise when embedding JSON in HTML.\n\t//\n\t// In non-HTML settings where the escaping interferes with the readability\n\t// of the output, SetEscapeHTML(false) disables this behavior.\n\tSetEscapeHTML(on bool)\n\n\t// Encode writes the JSON encoding of v to the stream,\n\t// followed by a newline character.\n\t//\n\t// See the documentation for Marshal for details about the\n\t// conversion of Go values to JSON.\n\tEncode(v any) error\n}"} {"repo":"gin","file":"codec/json/api.go","line":41,"symbol":"Decoder","kind":"type","lang":"go","doc":"Decoder an interface reads and decodes JSON values from an input stream.","code":"type Decoder interface {\n\t// UseNumber causes the Decoder to unmarshal a number into an any as a\n\t// Number instead of as a float64.\n\tUseNumber()\n\n\t// DisallowUnknownFields causes the Decoder to return an error when the destination\n\t// is a struct and the input contains object keys which do not match any\n\t// non-ignored, exported fields in the destination.\n\tDisallowUnknownFields()\n\n\t// Decode reads the next JSON-encoded value from its\n\t// input and stores it in the value pointed to by v.\n\t//\n\t// See the documentation for Unmarshal for details about\n\t// the conversion of JSON into a Go value.\n\tDecode(v any) error\n}"} {"repo":"gin","file":"codec/json/go_json.go","line":16,"symbol":"Package","kind":"constant","lang":"go","doc":"Package indicates what library is being used for JSON encoding.","code":"Package = \"github.com/goccy/go-json\""} {"repo":"gin","file":"codec/json/go_json.go","line":18,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tAPI = gojsonApi{}\n}"} {"repo":"gin","file":"codec/json/go_json.go","line":22,"symbol":"gojsonApi","kind":"type","lang":"go","code":"type gojsonApi struct{}"} {"repo":"gin","file":"codec/json/go_json.go","line":24,"symbol":"Marshal","kind":"method","lang":"go","code":"func (j gojsonApi) Marshal(v any) ([]byte, error) {\n\treturn json.Marshal(v)\n}"} {"repo":"gin","file":"codec/json/go_json.go","line":28,"symbol":"Unmarshal","kind":"method","lang":"go","code":"func (j gojsonApi) Unmarshal(data []byte, v any) error {\n\treturn json.Unmarshal(data, v)\n}"} {"repo":"gin","file":"codec/json/go_json.go","line":32,"symbol":"MarshalIndent","kind":"method","lang":"go","code":"func (j gojsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {\n\treturn json.MarshalIndent(v, prefix, indent)\n}"} {"repo":"gin","file":"codec/json/go_json.go","line":36,"symbol":"NewEncoder","kind":"method","lang":"go","code":"func (j gojsonApi) NewEncoder(writer io.Writer) Encoder {\n\treturn json.NewEncoder(writer)\n}"} {"repo":"gin","file":"codec/json/go_json.go","line":40,"symbol":"NewDecoder","kind":"method","lang":"go","code":"func (j gojsonApi) NewDecoder(reader io.Reader) Decoder {\n\treturn json.NewDecoder(reader)\n}"} {"repo":"gin","file":"codec/json/json.go","line":15,"symbol":"Package","kind":"constant","lang":"go","doc":"Package indicates what library is being used for JSON encoding.","code":"Package = \"encoding/json\""} {"repo":"gin","file":"codec/json/json.go","line":17,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tAPI = jsonApi{}\n}"} {"repo":"gin","file":"codec/json/json.go","line":21,"symbol":"jsonApi","kind":"type","lang":"go","code":"type jsonApi struct{}"} {"repo":"gin","file":"codec/json/json.go","line":23,"symbol":"Marshal","kind":"method","lang":"go","code":"func (j jsonApi) Marshal(v any) ([]byte, error) {\n\treturn json.Marshal(v)\n}"} {"repo":"gin","file":"codec/json/json.go","line":27,"symbol":"Unmarshal","kind":"method","lang":"go","code":"func (j jsonApi) Unmarshal(data []byte, v any) error {\n\treturn json.Unmarshal(data, v)\n}"} {"repo":"gin","file":"codec/json/json.go","line":31,"symbol":"MarshalIndent","kind":"method","lang":"go","code":"func (j jsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {\n\treturn json.MarshalIndent(v, prefix, indent)\n}"} {"repo":"gin","file":"codec/json/json.go","line":35,"symbol":"NewEncoder","kind":"method","lang":"go","code":"func (j jsonApi) NewEncoder(writer io.Writer) Encoder {\n\treturn json.NewEncoder(writer)\n}"} {"repo":"gin","file":"codec/json/json.go","line":39,"symbol":"NewDecoder","kind":"method","lang":"go","code":"func (j jsonApi) NewDecoder(reader io.Reader) Decoder {\n\treturn json.NewDecoder(reader)\n}"} {"repo":"gin","file":"codec/json/jsoniter.go","line":16,"symbol":"Package","kind":"constant","lang":"go","doc":"Package indicates what library is being used for JSON encoding.","code":"Package = \"github.com/json-iterator/go\""} {"repo":"gin","file":"codec/json/jsoniter.go","line":18,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tAPI = jsoniterApi{}\n}"} {"repo":"gin","file":"codec/json/jsoniter.go","line":22,"symbol":"json","kind":"variable","lang":"go","code":"json = jsoniter.ConfigCompatibleWithStandardLibrary"} {"repo":"gin","file":"codec/json/jsoniter.go","line":24,"symbol":"jsoniterApi","kind":"type","lang":"go","code":"type jsoniterApi struct{}"} {"repo":"gin","file":"codec/json/jsoniter.go","line":26,"symbol":"Marshal","kind":"method","lang":"go","code":"func (j jsoniterApi) Marshal(v any) ([]byte, error) {\n\treturn json.Marshal(v)\n}"} {"repo":"gin","file":"codec/json/jsoniter.go","line":30,"symbol":"Unmarshal","kind":"method","lang":"go","code":"func (j jsoniterApi) Unmarshal(data []byte, v any) error {\n\treturn json.Unmarshal(data, v)\n}"} {"repo":"gin","file":"codec/json/jsoniter.go","line":34,"symbol":"MarshalIndent","kind":"method","lang":"go","code":"func (j jsoniterApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {\n\treturn json.MarshalIndent(v, prefix, indent)\n}"} {"repo":"gin","file":"codec/json/jsoniter.go","line":38,"symbol":"NewEncoder","kind":"method","lang":"go","code":"func (j jsoniterApi) NewEncoder(writer io.Writer) Encoder {\n\treturn json.NewEncoder(writer)\n}"} {"repo":"gin","file":"codec/json/jsoniter.go","line":42,"symbol":"NewDecoder","kind":"method","lang":"go","code":"func (j jsoniterApi) NewDecoder(reader io.Reader) Decoder {\n\treturn json.NewDecoder(reader)\n}"} {"repo":"gin","file":"codec/json/sonic.go","line":16,"symbol":"Package","kind":"constant","lang":"go","doc":"Package indicates what library is being used for JSON encoding.","code":"Package = \"github.com/bytedance/sonic\""} {"repo":"gin","file":"codec/json/sonic.go","line":18,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tAPI = sonicApi{}\n}"} {"repo":"gin","file":"codec/json/sonic.go","line":22,"symbol":"json","kind":"variable","lang":"go","code":"json = sonic.ConfigStd"} {"repo":"gin","file":"codec/json/sonic.go","line":24,"symbol":"sonicApi","kind":"type","lang":"go","code":"type sonicApi struct{}"} {"repo":"gin","file":"codec/json/sonic.go","line":26,"symbol":"Marshal","kind":"method","lang":"go","code":"func (j sonicApi) Marshal(v any) ([]byte, error) {\n\treturn json.Marshal(v)\n}"} {"repo":"gin","file":"codec/json/sonic.go","line":30,"symbol":"Unmarshal","kind":"method","lang":"go","code":"func (j sonicApi) Unmarshal(data []byte, v any) error {\n\treturn json.Unmarshal(data, v)\n}"} {"repo":"gin","file":"codec/json/sonic.go","line":34,"symbol":"MarshalIndent","kind":"method","lang":"go","code":"func (j sonicApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {\n\treturn json.MarshalIndent(v, prefix, indent)\n}"} {"repo":"gin","file":"codec/json/sonic.go","line":38,"symbol":"NewEncoder","kind":"method","lang":"go","code":"func (j sonicApi) NewEncoder(writer io.Writer) Encoder {\n\treturn json.NewEncoder(writer)\n}"} {"repo":"gin","file":"codec/json/sonic.go","line":42,"symbol":"NewDecoder","kind":"method","lang":"go","code":"func (j sonicApi) NewDecoder(reader io.Reader) Decoder {\n\treturn json.NewDecoder(reader)\n}"} {"repo":"gin","file":"context.go","line":32,"symbol":"MIMEJSON","kind":"constant","lang":"go","code":"MIMEJSON = binding.MIMEJSON"} {"repo":"gin","file":"context.go","line":33,"symbol":"MIMEHTML","kind":"constant","lang":"go","code":"MIMEHTML = binding.MIMEHTML"} {"repo":"gin","file":"context.go","line":34,"symbol":"MIMEXML","kind":"constant","lang":"go","code":"MIMEXML = binding.MIMEXML"} {"repo":"gin","file":"context.go","line":35,"symbol":"MIMEXML2","kind":"constant","lang":"go","code":"MIMEXML2 = binding.MIMEXML2"} {"repo":"gin","file":"context.go","line":36,"symbol":"MIMEPlain","kind":"constant","lang":"go","code":"MIMEPlain = binding.MIMEPlain"} {"repo":"gin","file":"context.go","line":37,"symbol":"MIMEPOSTForm","kind":"constant","lang":"go","code":"MIMEPOSTForm = binding.MIMEPOSTForm"} {"repo":"gin","file":"context.go","line":38,"symbol":"MIMEMultipartPOSTForm","kind":"constant","lang":"go","code":"MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm"} {"repo":"gin","file":"context.go","line":39,"symbol":"MIMEYAML","kind":"constant","lang":"go","code":"MIMEYAML = binding.MIMEYAML"} {"repo":"gin","file":"context.go","line":40,"symbol":"MIMEYAML2","kind":"constant","lang":"go","code":"MIMEYAML2 = binding.MIMEYAML2"} {"repo":"gin","file":"context.go","line":41,"symbol":"MIMETOML","kind":"constant","lang":"go","code":"MIMETOML = binding.MIMETOML"} {"repo":"gin","file":"context.go","line":42,"symbol":"MIMEPROTOBUF","kind":"constant","lang":"go","code":"MIMEPROTOBUF = binding.MIMEPROTOBUF"} {"repo":"gin","file":"context.go","line":43,"symbol":"MIMEBSON","kind":"constant","lang":"go","code":"MIMEBSON = binding.MIMEBSON"} {"repo":"gin","file":"context.go","line":47,"symbol":"BodyBytesKey","kind":"constant","lang":"go","doc":"BodyBytesKey indicates a default body bytes key.","code":"BodyBytesKey = \"_gin-gonic/gin/bodybyteskey\""} {"repo":"gin","file":"context.go","line":50,"symbol":"ContextKey","kind":"constant","lang":"go","doc":"ContextKey is the key that a Context returns itself for.","code":"ContextKey = \"_gin-gonic/gin/contextkey\""} {"repo":"gin","file":"context.go","line":52,"symbol":"ContextKeyType","kind":"type","lang":"go","code":"type ContextKeyType int"} {"repo":"gin","file":"context.go","line":54,"symbol":"ContextRequestKey","kind":"constant","lang":"go","code":"ContextRequestKey ContextKeyType = 0"} {"repo":"gin","file":"context.go","line":57,"symbol":"abortIndex","kind":"constant","lang":"go","doc":"abortIndex represents a typical value used in abort functions.","code":"abortIndex int8 = math.MaxInt8 >> 1"} {"repo":"gin","file":"context.go","line":61,"symbol":"Context","kind":"type","lang":"go","doc":"Context is the most important part of gin. It allows us to pass variables between middleware, manage the flow, validate the JSON of a request and render a JSON response for example.","code":"type Context struct {\n\twritermem responseWriter\n\tRequest *http.Request\n\tWriter ResponseWriter\n\n\tParams Params\n\thandlers HandlersChain\n\tindex int8\n\tfullPath string\n\n\tengine *Engine\n\tparams *Params\n\tskippedNodes *[]skippedNode\n\n\t// This mutex protects Keys map.\n\tmu sync.RWMutex\n\n\t// Keys is a key/value pair exclusively for the context of each request.\n\tKeys map[any]any\n\n\t// Errors is a list of errors attached to all the handlers/middlewares who used this context.\n\tErrors errorMsgs\n\n\t// Accepted defines a list of manually accepted formats for content negotiation.\n\tAccepted []string\n\n\t// queryCache caches the query result from c.Request.URL.Query().\n\tqueryCache url.Values\n\n\t// formCache caches c.Request.PostForm, which contains the parsed form data from POST, PATCH,\n\t// or PUT body parameters.\n\tformCache url.Values\n\n\t// SameSite allows a server to define a cookie attribute making it impossible for\n\t// the browser to send this cookie along with cross-site requests.\n\tsameSite http.SameSite\n}"} {"repo":"gin","file":"context.go","line":103,"symbol":"reset","kind":"method","lang":"go","code":"func (c *Context) reset() {\n\tc.Writer = &c.writermem\n\tc.Params = c.Params[:0]\n\tc.handlers = nil\n\tc.index = -1\n\n\tc.fullPath = \"\"\n\tc.Keys = nil\n\tc.Errors = c.Errors[:0]\n\tc.Accepted = nil\n\tc.queryCache = nil\n\tc.formCache = nil\n\tc.sameSite = 0\n\t*c.params = (*c.params)[:0]\n\t*c.skippedNodes = (*c.skippedNodes)[:0]\n}"} {"repo":"gin","file":"context.go","line":122,"symbol":"Copy","kind":"method","lang":"go","doc":"Copy returns a copy of the current context that can be safely used outside the request's scope. This has to be used when the context has to be passed to a goroutine.","code":"func (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tengine: c.engine,\n\t}\n\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.fullPath = c.fullPath\n\n\tc.mu.RLock()\n\tcp.Keys = maps.Clone(c.Keys)\n\tc.mu.RUnlock()\n\n\tcParams := c.Params\n\tcp.Params = make([]Param, len(cParams))\n\tcopy(cp.Params, cParams)\n\n\tif c.Errors != nil {\n\t\tcp.Errors = make(errorMsgs, len(c.Errors))\n\t\tcopy(cp.Errors, c.Errors)\n\t}\n\n\tif c.Accepted != nil {\n\t\tcp.Accepted = make([]string, len(c.Accepted))\n\t\tcopy(cp.Accepted, c.Accepted)\n\t}\n\n\treturn &cp\n}"} {"repo":"gin","file":"context.go","line":158,"symbol":"HandlerName","kind":"method","lang":"go","doc":"HandlerName returns the main handler's name. For example if the handler is \"handleGetUsers()\", this function will return \"main.handleGetUsers\".","code":"func (c *Context) HandlerName() string {\n\treturn nameOfFunction(c.handlers.Last())\n}"} {"repo":"gin","file":"context.go","line":164,"symbol":"HandlerNames","kind":"method","lang":"go","doc":"HandlerNames returns a list of all registered handlers for this context in descending order, following the semantics of HandlerName()","code":"func (c *Context) HandlerNames() []string {\n\thn := make([]string, 0, len(c.handlers))\n\tfor _, val := range c.handlers {\n\t\tif val == nil {\n\t\t\tcontinue\n\t\t}\n\t\thn = append(hn, nameOfFunction(val))\n\t}\n\treturn hn\n}"} {"repo":"gin","file":"context.go","line":176,"symbol":"Handler","kind":"method","lang":"go","doc":"Handler returns the main handler.","code":"func (c *Context) Handler() HandlerFunc {\n\treturn c.handlers.Last()\n}"} {"repo":"gin","file":"context.go","line":186,"symbol":"FullPath","kind":"method","lang":"go","doc":"FullPath returns a matched route full path. For not found routes returns an empty string. router.GET(\"/user/:id\", func(c *gin.Context) { c.FullPath() == \"/user/:id\" // true })","code":"func (c *Context) FullPath() string {\n\treturn c.fullPath\n}"} {"repo":"gin","file":"context.go","line":197,"symbol":"Next","kind":"method","lang":"go","doc":"Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler. See example in GitHub.","code":"func (c *Context) Next() {\n\tc.index++\n\tfor c.index < safeInt8(len(c.handlers)) {\n\t\tif c.handlers[c.index] != nil {\n\t\t\tc.handlers[c.index](c)\n\t\t}\n\t\tc.index++\n\t}\n}"} {"repo":"gin","file":"context.go","line":208,"symbol":"IsAborted","kind":"method","lang":"go","doc":"IsAborted returns true if the current context was aborted.","code":"func (c *Context) IsAborted() bool {\n\treturn c.index >= abortIndex\n}"} {"repo":"gin","file":"context.go","line":216,"symbol":"Abort","kind":"method","lang":"go","doc":"Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.","code":"func (c *Context) Abort() {\n\tc.index = abortIndex\n}"} {"repo":"gin","file":"context.go","line":222,"symbol":"AbortWithStatus","kind":"method","lang":"go","doc":"AbortWithStatus calls `Abort()` and writes the headers with the specified status code. For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).","code":"func (c *Context) AbortWithStatus(code int) {\n\tc.Status(code)\n\tc.Writer.WriteHeaderNow()\n\tc.Abort()\n}"} {"repo":"gin","file":"context.go","line":231,"symbol":"AbortWithStatusPureJSON","kind":"method","lang":"go","doc":"AbortWithStatusPureJSON calls `Abort()` and then `PureJSON` internally. This method stops the chain, writes the status code and return a JSON body without escaping. It also sets the Content-Type as \"application/json\".","code":"func (c *Context) AbortWithStatusPureJSON(code int, jsonObj any) {\n\tc.Abort()\n\tc.PureJSON(code, jsonObj)\n}"} {"repo":"gin","file":"context.go","line":239,"symbol":"AbortWithStatusJSON","kind":"method","lang":"go","doc":"AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body. It also sets the Content-Type as \"application/json\".","code":"func (c *Context) AbortWithStatusJSON(code int, jsonObj any) {\n\tc.Abort()\n\tc.JSON(code, jsonObj)\n}"} {"repo":"gin","file":"context.go","line":247,"symbol":"AbortWithError","kind":"method","lang":"go","doc":"AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and pushes the specified error to `c.Errors`. See Context.Error() for more details.","code":"func (c *Context) AbortWithError(code int, err error) *Error {\n\tc.AbortWithStatus(code)\n\treturn c.Error(err)\n}"} {"repo":"gin","file":"context.go","line":261,"symbol":"Error","kind":"method","lang":"go","doc":"Error attaches an error to the current context. The error is pushed to a list of errors. It's a good idea to call Error for each error that occurred during the resolution of a request. A middleware can be used to collect all the errors and push them to a database together, print a log, or append it in the HTTP response. Error will panic if err is nil.","code":"func (c *Context) Error(err error) *Error {\n\tif err == nil {\n\t\tpanic(\"err is nil\")\n\t}\n\n\tvar parsedError *Error\n\tok := errors.As(err, &parsedError)\n\tif !ok {\n\t\tparsedError = &Error{\n\t\t\tErr: err,\n\t\t\tType: ErrorTypePrivate,\n\t\t}\n\t}\n\n\tc.Errors = append(c.Errors, parsedError)\n\treturn parsedError\n}"} {"repo":"gin","file":"context.go","line":266,"symbol":"parsedError","kind":"variable","lang":"go","code":"parsedError *Error"} {"repo":"gin","file":"context.go","line":285,"symbol":"Set","kind":"method","lang":"go","doc":"Set is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.","code":"func (c *Context) Set(key any, value any) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tif c.Keys == nil {\n\t\tc.Keys = make(map[any]any)\n\t}\n\n\tc.Keys[key] = value\n}"} {"repo":"gin","file":"context.go","line":297,"symbol":"Get","kind":"method","lang":"go","doc":"Get returns the value for the given key, ie: (value, true). If the value does not exist it returns (nil, false)","code":"func (c *Context) Get(key any) (value any, exists bool) {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\tvalue, exists = c.Keys[key]\n\treturn\n}"} {"repo":"gin","file":"context.go","line":305,"symbol":"MustGet","kind":"method","lang":"go","doc":"MustGet returns the value for the given key if it exists, otherwise it panics.","code":"func (c *Context) MustGet(key any) any {\n\tif value, exists := c.Get(key); exists {\n\t\treturn value\n\t}\n\tpanic(fmt.Sprintf(\"key %v does not exist\", key))\n}"} {"repo":"gin","file":"context.go","line":312,"symbol":"getTyped","kind":"function","lang":"go","code":"func getTyped[T any](c *Context, key any) (res T) {\n\tif val, ok := c.Get(key); ok && val != nil {\n\t\tres, _ = val.(T)\n\t}\n\treturn\n}"} {"repo":"gin","file":"context.go","line":320,"symbol":"GetString","kind":"method","lang":"go","doc":"GetString returns the value associated with the key as a string.","code":"func (c *Context) GetString(key any) string {\n\treturn getTyped[string](c, key)\n}"} {"repo":"gin","file":"context.go","line":325,"symbol":"GetBool","kind":"method","lang":"go","doc":"GetBool returns the value associated with the key as a boolean.","code":"func (c *Context) GetBool(key any) bool {\n\treturn getTyped[bool](c, key)\n}"} {"repo":"gin","file":"context.go","line":330,"symbol":"GetInt","kind":"method","lang":"go","doc":"GetInt returns the value associated with the key as an integer.","code":"func (c *Context) GetInt(key any) int {\n\treturn getTyped[int](c, key)\n}"} {"repo":"gin","file":"context.go","line":335,"symbol":"GetInt8","kind":"method","lang":"go","doc":"GetInt8 returns the value associated with the key as an integer 8.","code":"func (c *Context) GetInt8(key any) int8 {\n\treturn getTyped[int8](c, key)\n}"} {"repo":"gin","file":"context.go","line":340,"symbol":"GetInt16","kind":"method","lang":"go","doc":"GetInt16 returns the value associated with the key as an integer 16.","code":"func (c *Context) GetInt16(key any) int16 {\n\treturn getTyped[int16](c, key)\n}"} {"repo":"gin","file":"context.go","line":345,"symbol":"GetInt32","kind":"method","lang":"go","doc":"GetInt32 returns the value associated with the key as an integer 32.","code":"func (c *Context) GetInt32(key any) int32 {\n\treturn getTyped[int32](c, key)\n}"} {"repo":"gin","file":"context.go","line":350,"symbol":"GetInt64","kind":"method","lang":"go","doc":"GetInt64 returns the value associated with the key as an integer 64.","code":"func (c *Context) GetInt64(key any) int64 {\n\treturn getTyped[int64](c, key)\n}"} {"repo":"gin","file":"context.go","line":355,"symbol":"GetUint","kind":"method","lang":"go","doc":"GetUint returns the value associated with the key as an unsigned integer.","code":"func (c *Context) GetUint(key any) uint {\n\treturn getTyped[uint](c, key)\n}"} {"repo":"gin","file":"context.go","line":360,"symbol":"GetUint8","kind":"method","lang":"go","doc":"GetUint8 returns the value associated with the key as an unsigned integer 8.","code":"func (c *Context) GetUint8(key any) uint8 {\n\treturn getTyped[uint8](c, key)\n}"} {"repo":"gin","file":"context.go","line":365,"symbol":"GetUint16","kind":"method","lang":"go","doc":"GetUint16 returns the value associated with the key as an unsigned integer 16.","code":"func (c *Context) GetUint16(key any) uint16 {\n\treturn getTyped[uint16](c, key)\n}"} {"repo":"gin","file":"context.go","line":370,"symbol":"GetUint32","kind":"method","lang":"go","doc":"GetUint32 returns the value associated with the key as an unsigned integer 32.","code":"func (c *Context) GetUint32(key any) uint32 {\n\treturn getTyped[uint32](c, key)\n}"} {"repo":"gin","file":"context.go","line":375,"symbol":"GetUint64","kind":"method","lang":"go","doc":"GetUint64 returns the value associated with the key as an unsigned integer 64.","code":"func (c *Context) GetUint64(key any) uint64 {\n\treturn getTyped[uint64](c, key)\n}"} {"repo":"gin","file":"context.go","line":380,"symbol":"GetFloat32","kind":"method","lang":"go","doc":"GetFloat32 returns the value associated with the key as a float32.","code":"func (c *Context) GetFloat32(key any) float32 {\n\treturn getTyped[float32](c, key)\n}"} {"repo":"gin","file":"context.go","line":385,"symbol":"GetFloat64","kind":"method","lang":"go","doc":"GetFloat64 returns the value associated with the key as a float64.","code":"func (c *Context) GetFloat64(key any) float64 {\n\treturn getTyped[float64](c, key)\n}"} {"repo":"gin","file":"context.go","line":390,"symbol":"GetTime","kind":"method","lang":"go","doc":"GetTime returns the value associated with the key as time.","code":"func (c *Context) GetTime(key any) time.Time {\n\treturn getTyped[time.Time](c, key)\n}"} {"repo":"gin","file":"context.go","line":395,"symbol":"GetDuration","kind":"method","lang":"go","doc":"GetDuration returns the value associated with the key as a duration.","code":"func (c *Context) GetDuration(key any) time.Duration {\n\treturn getTyped[time.Duration](c, key)\n}"} {"repo":"gin","file":"context.go","line":400,"symbol":"GetError","kind":"method","lang":"go","doc":"GetError returns the value associated with the key as an error.","code":"func (c *Context) GetError(key any) error {\n\treturn getTyped[error](c, key)\n}"} {"repo":"gin","file":"context.go","line":405,"symbol":"GetIntSlice","kind":"method","lang":"go","doc":"GetIntSlice returns the value associated with the key as a slice of integers.","code":"func (c *Context) GetIntSlice(key any) []int {\n\treturn getTyped[[]int](c, key)\n}"} {"repo":"gin","file":"context.go","line":410,"symbol":"GetInt8Slice","kind":"method","lang":"go","doc":"GetInt8Slice returns the value associated with the key as a slice of int8 integers.","code":"func (c *Context) GetInt8Slice(key any) []int8 {\n\treturn getTyped[[]int8](c, key)\n}"} {"repo":"gin","file":"context.go","line":415,"symbol":"GetInt16Slice","kind":"method","lang":"go","doc":"GetInt16Slice returns the value associated with the key as a slice of int16 integers.","code":"func (c *Context) GetInt16Slice(key any) []int16 {\n\treturn getTyped[[]int16](c, key)\n}"} {"repo":"gin","file":"context.go","line":420,"symbol":"GetInt32Slice","kind":"method","lang":"go","doc":"GetInt32Slice returns the value associated with the key as a slice of int32 integers.","code":"func (c *Context) GetInt32Slice(key any) []int32 {\n\treturn getTyped[[]int32](c, key)\n}"} {"repo":"gin","file":"context.go","line":425,"symbol":"GetInt64Slice","kind":"method","lang":"go","doc":"GetInt64Slice returns the value associated with the key as a slice of int64 integers.","code":"func (c *Context) GetInt64Slice(key any) []int64 {\n\treturn getTyped[[]int64](c, key)\n}"} {"repo":"gin","file":"context.go","line":430,"symbol":"GetUintSlice","kind":"method","lang":"go","doc":"GetUintSlice returns the value associated with the key as a slice of unsigned integers.","code":"func (c *Context) GetUintSlice(key any) []uint {\n\treturn getTyped[[]uint](c, key)\n}"} {"repo":"gin","file":"context_appengine.go","line":9,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tdefaultPlatform = PlatformGoogleAppEngine\n}"} {"repo":"gin","file":"context_file_test.go","line":12,"symbol":"TestContextFileSimple","kind":"function","lang":"go","doc":"TestContextFileSimple tests the Context.File() method with a simple case","code":"func TestContextFileSimple(t *testing.T) {\n\t// Test serving an existing file\n\ttestFile := \"testdata/test_file.txt\"\n\tw := httptest.NewRecorder()\n\tc, _ := CreateTestContext(w)\n\tc.Request = httptest.NewRequest(http.MethodGet, \"/test\", nil)\n\n\tc.File(testFile)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Contains(t, w.Body.String(), \"This is a test file\")\n\tassert.Equal(t, \"text/plain; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"context_file_test.go","line":27,"symbol":"TestContextFileNotFound","kind":"function","lang":"go","doc":"TestContextFileNotFound tests serving a non-existent file","code":"func TestContextFileNotFound(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tc, _ := CreateTestContext(w)\n\tc.Request = httptest.NewRequest(http.MethodGet, \"/test\", nil)\n\n\tc.File(\"non_existent_file.txt\")\n\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n}"} {"repo":"gin","file":"context_test.go","line":40,"symbol":"_","kind":"variable","lang":"go","code":"_ context.Context = (*Context)(nil)"} {"repo":"gin","file":"context_test.go","line":42,"symbol":"errTestRender","kind":"variable","lang":"go","code":"errTestRender = errors.New(\"TestRender\")"} {"repo":"gin","file":"context_test.go","line":50,"symbol":"createMultipartRequest","kind":"function","lang":"go","code":"func createMultipartRequest() *http.Request {\n\tboundary := \"--testboundary\"\n\tbody := new(bytes.Buffer)\n\tmw := multipart.NewWriter(body)\n\tdefer mw.Close()\n\n\tmust(mw.SetBoundary(boundary))\n\tmust(mw.WriteField(\"foo\", \"bar\"))\n\tmust(mw.WriteField(\"bar\", \"10\"))\n\tmust(mw.WriteField(\"bar\", \"foo2\"))\n\tmust(mw.WriteField(\"array\", \"first\"))\n\tmust(mw.WriteField(\"array\", \"second\"))\n\tmust(mw.WriteField(\"id\", \"\"))\n\tmust(mw.WriteField(\"time_local\", \"31/12/2016 14:55\"))\n\tmust(mw.WriteField(\"time_utc\", \"31/12/2016 14:55\"))\n\tmust(mw.WriteField(\"time_location\", \"31/12/2016 14:55\"))\n\tmust(mw.WriteField(\"names[a]\", \"thinkerou\"))\n\tmust(mw.WriteField(\"names[b]\", \"tianou\"))\n\treq, err := http.NewRequest(http.MethodPost, \"/\", body)\n\tmust(err)\n\treq.Header.Set(\"Content-Type\", MIMEMultipartPOSTForm+\"; boundary=\"+boundary)\n\treturn req\n}"} {"repo":"gin","file":"context_test.go","line":74,"symbol":"must","kind":"function","lang":"go","code":"func must(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}"} {"repo":"gin","file":"context_test.go","line":81,"symbol":"TestContextFile","kind":"function","lang":"go","doc":"TestContextFile tests the Context.File() method","code":"func TestContextFile(t *testing.T) {\n\t// Test serving an existing file\n\tt.Run(\"serve existing file\", func(t *testing.T) {\n\t\t// Create a temporary test file\n\t\ttestFile := \"testdata/test_file.txt\"\n\n\t\tw := httptest.NewRecorder()\n\t\tc, _ := CreateTestContext(w)\n\t\tc.Request = httptest.NewRequest(http.MethodGet, \"/test\", nil)\n\n\t\tc.File(testFile)\n\n\t\tassert.Equal(t, http.StatusOK, w.Code)\n\t\tassert.Contains(t, w.Body.String(), \"This is a test file\")\n\t\tassert.Equal(t, \"text/plain; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\t})\n\n\t// Test serving a non-existent file\n\tt.Run(\"serve non-existent file\", func(t *testing.T) {\n\t\tw := httptest.NewRecorder()\n\t\tc, _ := CreateTestContext(w)\n\t\tc.Request = httptest.NewRequest(http.MethodGet, \"/test\", nil)\n\n\t\tc.File(\"non_existent_file.txt\")\n\n\t\tassert.Equal(t, http.StatusNotFound, w.Code)\n\t})\n\n\t// Test serving a directory (should return 200 with directory listing or 403 Forbidden)\n\tt.Run(\"serve directory\", func(t *testing.T) {\n\t\tw := httptest.NewRecorder()\n\t\tc, _ := CreateTestContext(w)\n\t\tc.Request = httptest.NewRequest(http.MethodGet, \"/test\", nil)\n\n\t\tc.File(\".\")\n\n\t\t// Directory serving can return either 200 (with listing) or 403 (forbidden)\n\t\tassert.Tr"} {"repo":"gin","file":"context_test.go","line":153,"symbol":"TestContextFormFile","kind":"function","lang":"go","code":"func TestContextFormFile(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\tmw := multipart.NewWriter(buf)\n\tw, err := mw.CreateFormFile(\"file\", \"test\")\n\trequire.NoError(t, err)\n\t_, err = w.Write([]byte(\"test\"))\n\trequire.NoError(t, err)\n\tmw.Close()\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Request, _ = http.NewRequest(http.MethodPost, \"/\", buf)\n\tc.Request.Header.Set(\"Content-Type\", mw.FormDataContentType())\n\tf, err := c.FormFile(\"file\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"test\", f.Filename)\n\n\trequire.NoError(t, c.SaveUploadedFile(f, \"test\"))\n}"} {"repo":"gin","file":"context_test.go","line":171,"symbol":"TestContextFormFileFailed","kind":"function","lang":"go","code":"func TestContextFormFileFailed(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\tmw := multipart.NewWriter(buf)\n\tmw.Close()\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Request, _ = http.NewRequest(http.MethodPost, \"/\", nil)\n\tc.Request.Header.Set(\"Content-Type\", mw.FormDataContentType())\n\tc.engine.MaxMultipartMemory = 8 << 20\n\tf, err := c.FormFile(\"file\")\n\trequire.Error(t, err)\n\tassert.Nil(t, f)\n}"} {"repo":"gin","file":"context_test.go","line":184,"symbol":"TestContextMultipartForm","kind":"function","lang":"go","code":"func TestContextMultipartForm(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\tmw := multipart.NewWriter(buf)\n\trequire.NoError(t, mw.WriteField(\"foo\", \"bar\"))\n\tw, err := mw.CreateFormFile(\"file\", \"test\")\n\trequire.NoError(t, err)\n\t_, err = w.Write([]byte(\"test\"))\n\trequire.NoError(t, err)\n\tmw.Close()\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Request, _ = http.NewRequest(http.MethodPost, \"/\", buf)\n\tc.Request.Header.Set(\"Content-Type\", mw.FormDataContentType())\n\tf, err := c.MultipartForm()\n\trequire.NoError(t, err)\n\tassert.NotNil(t, f)\n\n\trequire.NoError(t, c.SaveUploadedFile(f.File[\"file\"][0], \"test\"))\n}"} {"repo":"gin","file":"context_test.go","line":203,"symbol":"TestSaveUploadedOpenFailed","kind":"function","lang":"go","code":"func TestSaveUploadedOpenFailed(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\tmw := multipart.NewWriter(buf)\n\tmw.Close()\n\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Request, _ = http.NewRequest(http.MethodPost, \"/\", buf)\n\tc.Request.Header.Set(\"Content-Type\", mw.FormDataContentType())\n\n\tf := &multipart.FileHeader{\n\t\tFilename: \"file\",\n\t}\n\trequire.Error(t, c.SaveUploadedFile(f, \"test\"))\n}"} {"repo":"gin","file":"context_test.go","line":218,"symbol":"TestSaveUploadedCreateFailed","kind":"function","lang":"go","code":"func TestSaveUploadedCreateFailed(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\tmw := multipart.NewWriter(buf)\n\tw, err := mw.CreateFormFile(\"file\", \"test\")\n\trequire.NoError(t, err)\n\t_, err = w.Write([]byte(\"test\"))\n\trequire.NoError(t, err)\n\tmw.Close()\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Request, _ = http.NewRequest(http.MethodPost, \"/\", buf)\n\tc.Request.Header.Set(\"Content-Type\", mw.FormDataContentType())\n\tf, err := c.FormFile(\"file\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"test\", f.Filename)\n\n\trequire.Error(t, c.SaveUploadedFile(f, \"/\"))\n}"} {"repo":"gin","file":"context_test.go","line":236,"symbol":"TestSaveUploadedFileWithPermission","kind":"function","lang":"go","code":"func TestSaveUploadedFileWithPermission(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\tmw := multipart.NewWriter(buf)\n\tw, err := mw.CreateFormFile(\"file\", \"permission_test\")\n\trequire.NoError(t, err)\n\t_, err = w.Write([]byte(\"permission_test\"))\n\trequire.NoError(t, err)\n\tmw.Close()\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Request, _ = http.NewRequest(http.MethodPost, \"/\", buf)\n\tc.Request.Header.Set(\"Content-Type\", mw.FormDataContentType())\n\tf, err := c.FormFile(\"file\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"permission_test\", f.Filename)\n\tvar mode fs.FileMode = 0o755\n\tdst := filepath.Join(t.TempDir(), \"subdir\", \"permission_test\")\n\trequire.NoError(t, c.SaveUploadedFile(f, dst, mode))\n\tinfo, err := os.Stat(filepath.Dir(dst))\n\trequire.NoError(t, err)\n\tassert.Equal(t, mode, info.Mode().Perm())\n}"} {"repo":"gin","file":"context_test.go","line":250,"symbol":"mode","kind":"variable","lang":"go","code":"mode fs.FileMode = 0o755"} {"repo":"gin","file":"context_test.go","line":258,"symbol":"TestSaveUploadedFileWithPermissionFailed","kind":"function","lang":"go","code":"func TestSaveUploadedFileWithPermissionFailed(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\tmw := multipart.NewWriter(buf)\n\tw, err := mw.CreateFormFile(\"file\", \"permission_test\")\n\trequire.NoError(t, err)\n\t_, err = w.Write([]byte(\"permission_test\"))\n\trequire.NoError(t, err)\n\tmw.Close()\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Request, _ = http.NewRequest(http.MethodPost, \"/\", buf)\n\tc.Request.Header.Set(\"Content-Type\", mw.FormDataContentType())\n\tf, err := c.FormFile(\"file\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"permission_test\", f.Filename)\n\tvar mode fs.FileMode = 0o644\n\tdst := filepath.Join(t.TempDir(), \"test\", \"permission_test\")\n\trequire.Error(t, c.SaveUploadedFile(f, dst, mode))\n}"} {"repo":"gin","file":"context_test.go","line":272,"symbol":"mode","kind":"variable","lang":"go","code":"mode fs.FileMode = 0o644"} {"repo":"gin","file":"context_test.go","line":284,"symbol":"TestSaveUploadedFileToExistingDir","kind":"function","lang":"go","doc":"SaveUploadedFile must not call os.Chmod on a directory that already exists, because the process may not own it (e.g. /tmp on Linux/macOS), where chmod fails with \"operation not permitted\". This asserts the behavioral contract directly — a pre-existing directory's permissions are left unchanged — so it catches the regression on every platform, including environments (root/CI, user-owned $TMPDIR) where chmod on the temp dir would otherwise succeed.","code":"func TestSaveUploadedFileToExistingDir(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\tmw := multipart.NewWriter(buf)\n\tw, err := mw.CreateFormFile(\"file\", \"existing_dir_test\")\n\trequire.NoError(t, err)\n\t_, err = w.Write([]byte(\"existing_dir_test\"))\n\trequire.NoError(t, err)\n\tmw.Close()\n\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Request, _ = http.NewRequest(http.MethodPost, \"/\", buf)\n\tc.Request.Header.Set(\"Content-Type\", mw.FormDataContentType())\n\tf, err := c.FormFile(\"file\")\n\trequire.NoError(t, err)\n\n\t// A pre-existing directory owned by this process, set to a known mode.\n\tdir := t.TempDir()\n\trequire.NoError(t, os.Chmod(dir, 0o700))\n\n\t// Pass a perm that differs from the directory's current mode. The fix must\n\t// not apply it to the pre-existing directory; the old code chmod'd it\n\t// unconditionally, which also failed outright on unowned dirs like /tmp.\n\tdst := filepath.Join(dir, \"existing_dir_test.txt\")\n\trequire.NoError(t, c.SaveUploadedFile(f, dst, 0o755))\n\n\t// The pre-existing directory's permissions must be unchanged.\n\tinfo, err := os.Stat(dir)\n\trequire.NoError(t, err)\n\tassert.Equal(t, os.FileMode(0o700), info.Mode().Perm(),\n\t\t\"permissions of a pre-existing directory must "} {"repo":"gin","file":"context_test.go","line":321,"symbol":"TestContextReset","kind":"function","lang":"go","code":"func TestContextReset(t *testing.T) {\n\trouter := New()\n\tc := router.allocateContext(0)\n\tassert.Equal(t, c.engine, router)\n\n\tc.index = 2\n\tc.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}\n\tc.Params = Params{Param{}}\n\tc.Error(errors.New(\"test\")) //nolint: errcheck\n\tc.Set(\"foo\", \"bar\")\n\tc.reset()\n\n\tassert.False(t, c.IsAborted())\n\tassert.Nil(t, c.Keys)\n\tassert.Nil(t, c.Accepted)\n\tassert.Empty(t, c.Errors)\n\tassert.Empty(t, c.Errors.Errors())\n\tassert.Empty(t, c.Errors.ByType(ErrorTypeAny))\n\tassert.Empty(t, c.Params)\n\tassert.EqualValues(t, -1, c.index)\n\tassert.Equal(t, c.Writer.(*responseWriter), &c.writermem)\n}"} {"repo":"gin","file":"context_test.go","line":344,"symbol":"TestContextHandlers","kind":"function","lang":"go","code":"func TestContextHandlers(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tassert.Nil(t, c.handlers)\n\tassert.Nil(t, c.handlers.Last())\n\n\tc.handlers = HandlersChain{}\n\tassert.NotNil(t, c.handlers)\n\tassert.Nil(t, c.handlers.Last())\n\n\tf := func(c *Context) {}\n\tg := func(c *Context) {}\n\n\tc.handlers = HandlersChain{f}\n\tcompareFunc(t, f, c.handlers.Last())\n\n\tc.handlers = HandlersChain{f, g}\n\tcompareFunc(t, g, c.handlers.Last())\n}"} {"repo":"gin","file":"context_test.go","line":365,"symbol":"TestContextSetGet","kind":"function","lang":"go","doc":"TestContextSetGet tests that a parameter is set correctly on the current context and can be retrieved using Get.","code":"func TestContextSetGet(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"foo\", \"bar\")\n\n\tvalue, err := c.Get(\"foo\")\n\tassert.Equal(t, \"bar\", value)\n\tassert.True(t, err)\n\n\tvalue, err = c.Get(\"foo2\")\n\tassert.Nil(t, value)\n\tassert.False(t, err)\n\n\tassert.Equal(t, \"bar\", c.MustGet(\"foo\"))\n\tassert.Panicsf(t, func() {\n\t\tc.MustGet(\"no_exist\")\n\t}, \"key no_exist does not exist\")\n}"} {"repo":"gin","file":"context_test.go","line":383,"symbol":"TestContextSetGetAnyKey","kind":"function","lang":"go","code":"func TestContextSetGetAnyKey(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\n\ttype key struct{}\n\n\ttests := []struct {\n\t\tkey any\n\t}{\n\t\t{1},\n\t\t{int32(1)},\n\t\t{int64(1)},\n\t\t{uint(1)},\n\t\t{float32(1)},\n\t\t{key{}},\n\t\t{&key{}},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(reflect.TypeOf(tt.key).String(), func(t *testing.T) {\n\t\t\tc.Set(tt.key, 1)\n\t\t\tvalue, ok := c.Get(tt.key)\n\t\t\tassert.True(t, ok)\n\t\t\tassert.Equal(t, 1, value)\n\t\t})\n\t}\n}"} {"repo":"gin","file":"context_test.go","line":386,"symbol":"key","kind":"type","lang":"go","code":"type key struct{}"} {"repo":"gin","file":"context_test.go","line":410,"symbol":"TestContextSetGetPanicsWhenKeyNotComparable","kind":"function","lang":"go","code":"func TestContextSetGetPanicsWhenKeyNotComparable(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\n\tassert.Panics(t, func() {\n\t\tc.Set([]int{1}, 1)\n\t\tc.Set(func() {}, 1)\n\t\tc.Set(make(chan int), 1)\n\t})\n}"} {"repo":"gin","file":"context_test.go","line":420,"symbol":"TestContextSetGetValues","kind":"function","lang":"go","code":"func TestContextSetGetValues(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"string\", \"this is a string\")\n\tc.Set(\"int32\", int32(-42))\n\tc.Set(\"int64\", int64(42424242424242))\n\tc.Set(\"uint64\", uint64(42))\n\tc.Set(\"float32\", float32(4.2))\n\tc.Set(\"float64\", 4.2)\n\tvar a any = 1\n\tc.Set(\"intInterface\", a)\n\n\tassert.Exactly(t, \"this is a string\", c.MustGet(\"string\").(string))\n\tassert.Exactly(t, int32(-42), c.MustGet(\"int32\").(int32))\n\tassert.Exactly(t, int64(42424242424242), c.MustGet(\"int64\").(int64))\n\tassert.Exactly(t, uint64(42), c.MustGet(\"uint64\").(uint64))\n\tassert.InDelta(t, float32(4.2), c.MustGet(\"float32\").(float32), 0.01)\n\tassert.InDelta(t, 4.2, c.MustGet(\"float64\").(float64), 0.01)\n\tassert.Exactly(t, 1, c.MustGet(\"intInterface\").(int))\n}"} {"repo":"gin","file":"context_test.go","line":428,"symbol":"a","kind":"variable","lang":"go","code":"a any = 1"} {"repo":"gin","file":"context_test.go","line":440,"symbol":"TestContextGetString","kind":"function","lang":"go","code":"func TestContextGetString(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"string\", \"this is a string\")\n\tassert.Equal(t, \"this is a string\", c.GetString(\"string\"))\n}"} {"repo":"gin","file":"context_test.go","line":446,"symbol":"TestContextSetGetBool","kind":"function","lang":"go","code":"func TestContextSetGetBool(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"bool\", true)\n\tassert.True(t, c.GetBool(\"bool\"))\n}"} {"repo":"gin","file":"context_test.go","line":452,"symbol":"TestSetGetDelete","kind":"function","lang":"go","code":"func TestSetGetDelete(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"example-key\"\n\tvalue := \"example-value\"\n\tc.Set(key, value)\n\tval, exists := c.Get(key)\n\tassert.True(t, exists)\n\tassert.Equal(t, val, value)\n\tc.Delete(key)\n\t_, exists = c.Get(key)\n\tassert.False(t, exists)\n}"} {"repo":"gin","file":"context_test.go","line":465,"symbol":"TestContextGetInt","kind":"function","lang":"go","code":"func TestContextGetInt(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"int\", 1)\n\tassert.Equal(t, 1, c.GetInt(\"int\"))\n}"} {"repo":"gin","file":"context_test.go","line":471,"symbol":"TestContextGetInt8","kind":"function","lang":"go","code":"func TestContextGetInt8(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"int8\"\n\tvalue := int8(0x7F)\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetInt8(key))\n}"} {"repo":"gin","file":"context_test.go","line":479,"symbol":"TestContextGetInt16","kind":"function","lang":"go","code":"func TestContextGetInt16(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"int16\"\n\tvalue := int16(0x7FFF)\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetInt16(key))\n}"} {"repo":"gin","file":"context_test.go","line":487,"symbol":"TestContextGetInt32","kind":"function","lang":"go","code":"func TestContextGetInt32(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"int32\"\n\tvalue := int32(0x7FFFFFFF)\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetInt32(key))\n}"} {"repo":"gin","file":"context_test.go","line":495,"symbol":"TestContextGetInt64","kind":"function","lang":"go","code":"func TestContextGetInt64(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"int64\", int64(42424242424242))\n\tassert.Equal(t, int64(42424242424242), c.GetInt64(\"int64\"))\n}"} {"repo":"gin","file":"context_test.go","line":501,"symbol":"TestContextGetUint","kind":"function","lang":"go","code":"func TestContextGetUint(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"uint\", uint(1))\n\tassert.Equal(t, uint(1), c.GetUint(\"uint\"))\n}"} {"repo":"gin","file":"context_test.go","line":507,"symbol":"TestContextGetUint8","kind":"function","lang":"go","code":"func TestContextGetUint8(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"uint8\"\n\tvalue := uint8(0xFF)\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetUint8(key))\n}"} {"repo":"gin","file":"context_test.go","line":515,"symbol":"TestContextGetUint16","kind":"function","lang":"go","code":"func TestContextGetUint16(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"uint16\"\n\tvalue := uint16(0xFFFF)\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetUint16(key))\n}"} {"repo":"gin","file":"context_test.go","line":523,"symbol":"TestContextGetUint32","kind":"function","lang":"go","code":"func TestContextGetUint32(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"uint32\"\n\tvalue := uint32(0xFFFFFFFF)\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetUint32(key))\n}"} {"repo":"gin","file":"context_test.go","line":531,"symbol":"TestContextGetUint64","kind":"function","lang":"go","code":"func TestContextGetUint64(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"uint64\", uint64(18446744073709551615))\n\tassert.Equal(t, uint64(18446744073709551615), c.GetUint64(\"uint64\"))\n}"} {"repo":"gin","file":"context_test.go","line":537,"symbol":"TestContextGetFloat32","kind":"function","lang":"go","code":"func TestContextGetFloat32(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"float32\"\n\tvalue := float32(3.14)\n\tc.Set(key, value)\n\tassert.InDelta(t, value, c.GetFloat32(key), 0.01)\n}"} {"repo":"gin","file":"context_test.go","line":545,"symbol":"TestContextGetFloat64","kind":"function","lang":"go","code":"func TestContextGetFloat64(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"float64\", 4.2)\n\tassert.InDelta(t, 4.2, c.GetFloat64(\"float64\"), 0.01)\n}"} {"repo":"gin","file":"context_test.go","line":551,"symbol":"TestContextGetTime","kind":"function","lang":"go","code":"func TestContextGetTime(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tt1, _ := time.Parse(\"1/2/2006 15:04:05\", \"01/01/2017 12:00:00\")\n\tc.Set(\"time\", t1)\n\tassert.Equal(t, t1, c.GetTime(\"time\"))\n}"} {"repo":"gin","file":"context_test.go","line":558,"symbol":"TestContextGetDuration","kind":"function","lang":"go","code":"func TestContextGetDuration(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"duration\", time.Second)\n\tassert.Equal(t, time.Second, c.GetDuration(\"duration\"))\n}"} {"repo":"gin","file":"context_test.go","line":564,"symbol":"TestContextGetError","kind":"function","lang":"go","code":"func TestContextGetError(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"error\"\n\tvalue := errors.New(\"test error\")\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetError(key))\n}"} {"repo":"gin","file":"context_test.go","line":572,"symbol":"TestContextGetIntSlice","kind":"function","lang":"go","code":"func TestContextGetIntSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"int-slice\"\n\tvalue := []int{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetIntSlice(key))\n}"} {"repo":"gin","file":"context_test.go","line":580,"symbol":"TestContextGetInt8Slice","kind":"function","lang":"go","code":"func TestContextGetInt8Slice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"int8-slice\"\n\tvalue := []int8{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetInt8Slice(key))\n}"} {"repo":"gin","file":"context_test.go","line":588,"symbol":"TestContextGetInt16Slice","kind":"function","lang":"go","code":"func TestContextGetInt16Slice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"int16-slice\"\n\tvalue := []int16{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetInt16Slice(key))\n}"} {"repo":"gin","file":"context_test.go","line":596,"symbol":"TestContextGetInt32Slice","kind":"function","lang":"go","code":"func TestContextGetInt32Slice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"int32-slice\"\n\tvalue := []int32{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetInt32Slice(key))\n}"} {"repo":"gin","file":"context_test.go","line":604,"symbol":"TestContextGetInt64Slice","kind":"function","lang":"go","code":"func TestContextGetInt64Slice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"int64-slice\"\n\tvalue := []int64{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetInt64Slice(key))\n}"} {"repo":"gin","file":"context_test.go","line":612,"symbol":"TestContextGetUintSlice","kind":"function","lang":"go","code":"func TestContextGetUintSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"uint-slice\"\n\tvalue := []uint{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetUintSlice(key))\n}"} {"repo":"gin","file":"context_test.go","line":620,"symbol":"TestContextGetUint8Slice","kind":"function","lang":"go","code":"func TestContextGetUint8Slice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"uint8-slice\"\n\tvalue := []uint8{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetUint8Slice(key))\n}"} {"repo":"gin","file":"context_test.go","line":628,"symbol":"TestContextGetUint16Slice","kind":"function","lang":"go","code":"func TestContextGetUint16Slice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"uint16-slice\"\n\tvalue := []uint16{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetUint16Slice(key))\n}"} {"repo":"gin","file":"context_test.go","line":636,"symbol":"TestContextGetUint32Slice","kind":"function","lang":"go","code":"func TestContextGetUint32Slice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"uint32-slice\"\n\tvalue := []uint32{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetUint32Slice(key))\n}"} {"repo":"gin","file":"context_test.go","line":644,"symbol":"TestContextGetUint64Slice","kind":"function","lang":"go","code":"func TestContextGetUint64Slice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"uint64-slice\"\n\tvalue := []uint64{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetUint64Slice(key))\n}"} {"repo":"gin","file":"context_test.go","line":652,"symbol":"TestContextGetFloat32Slice","kind":"function","lang":"go","code":"func TestContextGetFloat32Slice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"float32-slice\"\n\tvalue := []float32{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetFloat32Slice(key))\n}"} {"repo":"gin","file":"context_test.go","line":660,"symbol":"TestContextGetFloat64Slice","kind":"function","lang":"go","code":"func TestContextGetFloat64Slice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"float64-slice\"\n\tvalue := []float64{1, 2}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetFloat64Slice(key))\n}"} {"repo":"gin","file":"context_test.go","line":668,"symbol":"TestContextGetStringSlice","kind":"function","lang":"go","code":"func TestContextGetStringSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.Set(\"slice\", []string{\"foo\"})\n\tassert.Equal(t, []string{\"foo\"}, c.GetStringSlice(\"slice\"))\n}"} {"repo":"gin","file":"context_test.go","line":674,"symbol":"TestContextGetErrorSlice","kind":"function","lang":"go","code":"func TestContextGetErrorSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tkey := \"error-slice\"\n\tvalue := []error{errors.New(\"error1\"), errors.New(\"error2\")}\n\tc.Set(key, value)\n\tassert.Equal(t, value, c.GetErrorSlice(key))\n}"} {"repo":"gin","file":"context_test.go","line":682,"symbol":"TestContextGetStringMap","kind":"function","lang":"go","code":"func TestContextGetStringMap(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tm := make(map[string]any)\n\tm[\"foo\"] = 1\n\tc.Set(\"map\", m)\n\n\tassert.Equal(t, m, c.GetStringMap(\"map\"))\n\tassert.Equal(t, 1, c.GetStringMap(\"map\")[\"foo\"])\n}"} {"repo":"gin","file":"context_test.go","line":692,"symbol":"TestContextGetStringMapString","kind":"function","lang":"go","code":"func TestContextGetStringMapString(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tm := make(map[string]string)\n\tm[\"foo\"] = \"bar\"\n\tc.Set(\"map\", m)\n\n\tassert.Equal(t, m, c.GetStringMapString(\"map\"))\n\tassert.Equal(t, \"bar\", c.GetStringMapString(\"map\")[\"foo\"])\n}"} {"repo":"gin","file":"context_test.go","line":702,"symbol":"TestContextGetStringMapStringSlice","kind":"function","lang":"go","code":"func TestContextGetStringMapStringSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tm := make(map[string][]string)\n\tm[\"foo\"] = []string{\"foo\"}\n\tc.Set(\"map\", m)\n\n\tassert.Equal(t, m, c.GetStringMapStringSlice(\"map\"))\n\tassert.Equal(t, []string{\"foo\"}, c.GetStringMapStringSlice(\"map\")[\"foo\"])\n}"} {"repo":"gin","file":"context_test.go","line":712,"symbol":"TestCopyConcurrentWithSet","kind":"function","lang":"go","code":"func TestCopyConcurrentWithSet(t *testing.T) {\n\tc := &Context{}\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < 100; i++ {\n\t\t\tc.Set(i, i)\n\t\t}\n\t}()\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < 100; i++ {\n\t\t\tcp := c.Copy()\n\t\t\tfor k, v := range cp.Keys {\n\t\t\t\tif k != v {\n\t\t\t\t\tt.Errorf(\"copied key %v = %v, want %v\", k, v, k)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\twg.Wait()\n}"} {"repo":"gin","file":"context_test.go","line":714,"symbol":"wg","kind":"variable","lang":"go","code":"wg sync.WaitGroup"} {"repo":"gin","file":"debug.go","line":16,"symbol":"ginSupportMinGoVer","kind":"constant","lang":"go","code":"ginSupportMinGoVer = 25"} {"repo":"gin","file":"debug.go","line":18,"symbol":"runtimeVersion","kind":"variable","lang":"go","code":"runtimeVersion = runtime.Version()"} {"repo":"gin","file":"debug.go","line":22,"symbol":"IsDebugging","kind":"function","lang":"go","doc":"IsDebugging returns true if the framework is running in debug mode. Use SetMode(gin.ReleaseMode) to disable debug mode.","code":"func IsDebugging() bool {\n\treturn atomic.LoadInt32(&ginMode) == debugCode\n}"} {"repo":"gin","file":"debug.go","line":27,"symbol":"DebugPrintRouteFunc","kind":"variable","lang":"go","doc":"DebugPrintRouteFunc indicates debug log output format.","code":"DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int)"} {"repo":"gin","file":"debug.go","line":30,"symbol":"DebugPrintFunc","kind":"variable","lang":"go","doc":"DebugPrintFunc indicates debug log output format.","code":"DebugPrintFunc func(format string, values ...any)"} {"repo":"gin","file":"debug.go","line":32,"symbol":"debugPrintRoute","kind":"function","lang":"go","code":"func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) {\n\tif IsDebugging() {\n\t\tnuHandlers := len(handlers)\n\t\thandlerName := nameOfFunction(handlers.Last())\n\t\tif DebugPrintRouteFunc == nil {\n\t\t\tdebugPrint(\"%-6s %-25s --> %s (%d handlers)\\n\", httpMethod, absolutePath, handlerName, nuHandlers)\n\t\t} else {\n\t\t\tDebugPrintRouteFunc(httpMethod, absolutePath, handlerName, nuHandlers)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"debug.go","line":44,"symbol":"debugPrintLoadTemplate","kind":"function","lang":"go","code":"func debugPrintLoadTemplate(tmpl *template.Template) {\n\tif IsDebugging() {\n\t\tvar buf strings.Builder\n\t\tfor _, tmpl := range tmpl.Templates() {\n\t\t\tbuf.WriteString(\"\\t- \")\n\t\t\tbuf.WriteString(tmpl.Name())\n\t\t\tbuf.WriteString(\"\\n\")\n\t\t}\n\t\tdebugPrint(\"Loaded HTML Templates (%d): \\n%s\\n\", len(tmpl.Templates()), buf.String())\n\t}\n}"} {"repo":"gin","file":"debug.go","line":46,"symbol":"buf","kind":"variable","lang":"go","code":"buf strings.Builder"} {"repo":"gin","file":"debug.go","line":56,"symbol":"debugPrint","kind":"function","lang":"go","code":"func debugPrint(format string, values ...any) {\n\tif !IsDebugging() {\n\t\treturn\n\t}\n\n\tif DebugPrintFunc != nil {\n\t\tDebugPrintFunc(format, values...)\n\t\treturn\n\t}\n\n\tif !strings.HasSuffix(format, \"\\n\") {\n\t\tformat += \"\\n\"\n\t}\n\tfmt.Fprintf(DefaultWriter, \"[GIN-debug] \"+format, values...)\n}"} {"repo":"gin","file":"debug.go","line":72,"symbol":"getMinVer","kind":"function","lang":"go","code":"func getMinVer(v string) (uint64, error) {\n\tfirst := strings.IndexByte(v, '.')\n\tlast := strings.LastIndexByte(v, '.')\n\tif first == last {\n\t\treturn strconv.ParseUint(v[first+1:], 10, 64)\n\t}\n\treturn strconv.ParseUint(v[first+1:last], 10, 64)\n}"} {"repo":"gin","file":"debug.go","line":81,"symbol":"debugPrintWARNINGDefault","kind":"function","lang":"go","code":"func debugPrintWARNINGDefault() {\n\tif v, e := getMinVer(runtimeVersion); e == nil && v < ginSupportMinGoVer {\n\t\tdebugPrint(`[WARNING] Now Gin requires Go 1.25+.\n\n`)\n\t}\n\tdebugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\n\n`)\n}"} {"repo":"gin","file":"debug.go","line":92,"symbol":"debugPrintWARNINGNew","kind":"function","lang":"go","code":"func debugPrintWARNINGNew() {\n\tdebugPrint(`[WARNING] Running in \"debug\" mode. Switch to \"release\" mode in production.\n - using env:\texport GIN_MODE=release\n - using code:\tgin.SetMode(gin.ReleaseMode)\n\n`)\n}"} {"repo":"gin","file":"debug.go","line":100,"symbol":"debugPrintWARNINGSetHTMLTemplate","kind":"function","lang":"go","code":"func debugPrintWARNINGSetHTMLTemplate() {\n\tdebugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called\nat initialization. ie. before any route is registered or the router is listening in a socket:\n\n\trouter := gin.Default()\n\trouter.SetHTMLTemplate(template) // << good place\n\n`)\n}"} {"repo":"gin","file":"debug.go","line":110,"symbol":"debugPrintError","kind":"function","lang":"go","code":"func debugPrintError(err error) {\n\tif err != nil && IsDebugging() {\n\t\tfmt.Fprintf(DefaultErrorWriter, \"[GIN-debug] [ERROR] %v\\n\", err)\n\t}\n}"} {"repo":"gin","file":"debug_test.go","line":23,"symbol":"TestIsDebugging","kind":"function","lang":"go","code":"func TestIsDebugging(t *testing.T) {\n\tSetMode(DebugMode)\n\tassert.True(t, IsDebugging())\n\tSetMode(ReleaseMode)\n\tassert.False(t, IsDebugging())\n\tSetMode(TestMode)\n\tassert.False(t, IsDebugging())\n}"} {"repo":"gin","file":"debug_test.go","line":32,"symbol":"TestDebugPrint","kind":"function","lang":"go","code":"func TestDebugPrint(t *testing.T) {\n\tre := captureOutput(t, func() {\n\t\tSetMode(DebugMode)\n\t\tSetMode(ReleaseMode)\n\t\tdebugPrint(\"DEBUG this!\")\n\t\tSetMode(TestMode)\n\t\tdebugPrint(\"DEBUG this!\")\n\t\tSetMode(DebugMode)\n\t\tdebugPrint(\"these are %d %s\", 2, \"error messages\")\n\t\tSetMode(TestMode)\n\t})\n\tassert.Equal(t, \"[GIN-debug] these are 2 error messages\\n\", re)\n}"} {"repo":"gin","file":"debug_test.go","line":46,"symbol":"TestDebugPrintFunc","kind":"function","lang":"go","code":"func TestDebugPrintFunc(t *testing.T) {\n\tDebugPrintFunc = func(format string, values ...any) {\n\t\tfmt.Fprintf(DefaultWriter, \"[GIN-debug] \"+format, values...)\n\t}\n\tre := captureOutput(t, func() {\n\t\tSetMode(DebugMode)\n\t\tdebugPrint(\"debug print func test: %d\", 123)\n\t\tSetMode(TestMode)\n\t})\n\tassert.Regexp(t, `^\\[GIN-debug\\] debug print func test: 123`, re)\n}"} {"repo":"gin","file":"debug_test.go","line":58,"symbol":"TestDebugPrintError","kind":"function","lang":"go","code":"func TestDebugPrintError(t *testing.T) {\n\tre := captureOutput(t, func() {\n\t\tSetMode(DebugMode)\n\t\tdebugPrintError(nil)\n\t\tdebugPrintError(errors.New(\"this is an error\"))\n\t\tSetMode(TestMode)\n\t})\n\tassert.Equal(t, \"[GIN-debug] [ERROR] this is an error\\n\", re)\n}"} {"repo":"gin","file":"debug_test.go","line":68,"symbol":"TestDebugPrintRoutes","kind":"function","lang":"go","code":"func TestDebugPrintRoutes(t *testing.T) {\n\tre := captureOutput(t, func() {\n\t\tSetMode(DebugMode)\n\t\tdebugPrintRoute(http.MethodGet, \"/path/to/route/:param\", HandlersChain{func(c *Context) {}, handlerNameTest})\n\t\tSetMode(TestMode)\n\t})\n\tassert.Regexp(t, `^\\[GIN-debug\\] GET /path/to/route/:param --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \\(2 handlers\\)\\n$`, re)\n}"} {"repo":"gin","file":"debug_test.go","line":77,"symbol":"TestDebugPrintRouteFunc","kind":"function","lang":"go","code":"func TestDebugPrintRouteFunc(t *testing.T) {\n\tDebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {\n\t\tfmt.Fprintf(DefaultWriter, \"[GIN-debug] %-6s %-40s --> %s (%d handlers)\\n\", httpMethod, absolutePath, handlerName, nuHandlers)\n\t}\n\tre := captureOutput(t, func() {\n\t\tSetMode(DebugMode)\n\t\tdebugPrintRoute(http.MethodGet, \"/path/to/route/:param1/:param2\", HandlersChain{func(c *Context) {}, handlerNameTest})\n\t\tSetMode(TestMode)\n\t})\n\tassert.Regexp(t, `^\\[GIN-debug\\] GET /path/to/route/:param1/:param2 --> (.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest \\(2 handlers\\)\\n$`, re)\n}"} {"repo":"gin","file":"debug_test.go","line":89,"symbol":"TestDebugPrintLoadTemplate","kind":"function","lang":"go","code":"func TestDebugPrintLoadTemplate(t *testing.T) {\n\tre := captureOutput(t, func() {\n\t\tSetMode(DebugMode)\n\t\ttempl := template.Must(template.New(\"\").Delims(\"{[{\", \"}]}\").ParseGlob(\"./testdata/template/hello.tmpl\"))\n\t\tdebugPrintLoadTemplate(templ)\n\t\tSetMode(TestMode)\n\t})\n\tassert.Regexp(t, `^\\[GIN-debug\\] Loaded HTML Templates \\(2\\): \\n(\\t- \\n|\\t- hello\\.tmpl\\n){2}\\n`, re)\n}"} {"repo":"gin","file":"debug_test.go","line":99,"symbol":"TestDebugPrintWARNINGSetHTMLTemplate","kind":"function","lang":"go","code":"func TestDebugPrintWARNINGSetHTMLTemplate(t *testing.T) {\n\tre := captureOutput(t, func() {\n\t\tSetMode(DebugMode)\n\t\tdebugPrintWARNINGSetHTMLTemplate()\n\t\tSetMode(TestMode)\n\t})\n\tassert.Equal(t, \"[GIN-debug] [WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called\\nat initialization. ie. before any route is registered or the router is listening in a socket:\\n\\n\\trouter := gin.Default()\\n\\trouter.SetHTMLTemplate(template) // << good place\\n\\n\", re)\n}"} {"repo":"gin","file":"debug_test.go","line":108,"symbol":"TestDebugPrintWARNINGDefault","kind":"function","lang":"go","code":"func TestDebugPrintWARNINGDefault(t *testing.T) {\n\tre := captureOutput(t, func() {\n\t\tSetMode(DebugMode)\n\t\tdebugPrintWARNINGDefault()\n\t\tSetMode(TestMode)\n\t})\n\tassert.Equal(t, \"[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\\n\\n\", re)\n}"} {"repo":"gin","file":"debug_test.go","line":117,"symbol":"TestDebugPrintWARNINGDefaultWithUnsupportedVersion","kind":"function","lang":"go","code":"func TestDebugPrintWARNINGDefaultWithUnsupportedVersion(t *testing.T) {\n\truntimeVersion = \"go1.23.12\"\n\tre := captureOutput(t, func() {\n\t\tSetMode(DebugMode)\n\t\tdebugPrintWARNINGDefault()\n\t\tSetMode(TestMode)\n\t})\n\tassert.Equal(t, \"[GIN-debug] [WARNING] Now Gin requires Go 1.25+.\\n\\n[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.\\n\\n\", re)\n}"} {"repo":"gin","file":"debug_test.go","line":127,"symbol":"TestDebugPrintWARNINGNew","kind":"function","lang":"go","code":"func TestDebugPrintWARNINGNew(t *testing.T) {\n\tre := captureOutput(t, func() {\n\t\tSetMode(DebugMode)\n\t\tdebugPrintWARNINGNew()\n\t\tSetMode(TestMode)\n\t})\n\tassert.Equal(t, \"[GIN-debug] [WARNING] Running in \\\"debug\\\" mode. Switch to \\\"release\\\" mode in production.\\n - using env:\\texport GIN_MODE=release\\n - using code:\\tgin.SetMode(gin.ReleaseMode)\\n\\n\", re)\n}"} {"repo":"gin","file":"debug_test.go","line":136,"symbol":"captureOutput","kind":"function","lang":"go","code":"func captureOutput(t *testing.T, f func()) string {\n\treader, writer, err := os.Pipe()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefaultWriter := DefaultWriter\n\tdefaultErrorWriter := DefaultErrorWriter\n\tdefer func() {\n\t\tDefaultWriter = defaultWriter\n\t\tDefaultErrorWriter = defaultErrorWriter\n\t\tlog.SetOutput(os.Stderr)\n\t}()\n\tDefaultWriter = writer\n\tDefaultErrorWriter = writer\n\tlog.SetOutput(writer)\n\tout := make(chan string)\n\twg := new(sync.WaitGroup)\n\twg.Add(1)\n\tgo func() {\n\t\tvar buf strings.Builder\n\t\twg.Done()\n\t\t_, err := io.Copy(&buf, reader)\n\t\tassert.NoError(t, err)\n\t\tout <- buf.String()\n\t}()\n\twg.Wait()\n\tf()\n\twriter.Close()\n\treturn <-out\n}"} {"repo":"gin","file":"debug_test.go","line":155,"symbol":"buf","kind":"variable","lang":"go","code":"buf strings.Builder"} {"repo":"gin","file":"debug_test.go","line":167,"symbol":"TestGetMinVer","kind":"function","lang":"go","code":"func TestGetMinVer(t *testing.T) {\n\tvar m uint64\n\tvar e error\n\t_, e = getMinVer(\"go1\")\n\trequire.Error(t, e)\n\tm, e = getMinVer(\"go1.1\")\n\tassert.Equal(t, uint64(1), m)\n\trequire.NoError(t, e)\n\tm, e = getMinVer(\"go1.1.1\")\n\trequire.NoError(t, e)\n\tassert.Equal(t, uint64(1), m)\n\t_, e = getMinVer(\"go1.1.1.1\")\n\trequire.Error(t, e)\n}"} {"repo":"gin","file":"debug_test.go","line":168,"symbol":"m","kind":"variable","lang":"go","code":"m uint64"} {"repo":"gin","file":"debug_test.go","line":169,"symbol":"e","kind":"variable","lang":"go","code":"e error"} {"repo":"gin","file":"deprecated.go","line":17,"symbol":"BindWith","kind":"method","lang":"go","doc":"BindWith binds the passed struct pointer using the specified binding engine. See the binding package. Deprecated: Use MustBindWith or ShouldBindWith.","code":"func (c *Context) BindWith(obj any, b binding.Binding) error {\n\tlog.Println(`BindWith(\\\"any, binding.Binding\\\") error is going to\n\tbe deprecated, please check issue #662 and either use MustBindWith() if you\n\twant HTTP 400 to be automatically returned if any error occur, or use\n\tShouldBindWith() if you need to manage the error.`)\n\treturn c.MustBindWith(obj, b)\n}"} {"repo":"gin","file":"deprecated_test.go","line":17,"symbol":"TestBindWith","kind":"function","lang":"go","code":"func TestBindWith(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tc, _ := CreateTestContext(w)\n\n\tc.Request, _ = http.NewRequest(http.MethodPost, \"/?foo=bar&bar=foo\", bytes.NewBufferString(\"foo=unused\"))\n\n\tvar obj struct {\n\t\tFoo string `form:\"foo\"`\n\t\tBar string `form:\"bar\"`\n\t}\n\tcaptureOutput(t, func() {\n\t\tassert.NoError(t, c.BindWith(&obj, binding.Form))\n\t})\n\tassert.Equal(t, \"foo\", obj.Bar)\n\tassert.Equal(t, \"bar\", obj.Foo)\n\tassert.Equal(t, 0, w.Body.Len())\n}"} {"repo":"gin","file":"deprecated_test.go","line":23,"symbol":"obj","kind":"variable","lang":"go","code":"obj struct {\n\t\tFoo string `form:\"foo\"`\n\t\tBar string `form:\"bar\"`\n\t}"} {"repo":"gin","file":"errors.go","line":16,"symbol":"ErrorType","kind":"type","lang":"go","doc":"ErrorType is an unsigned 64-bit error code as defined in the gin spec.","code":"type ErrorType uint64"} {"repo":"gin","file":"errors.go","line":20,"symbol":"ErrorTypeBind","kind":"constant","lang":"go","doc":"ErrorTypeBind is used when Context.Bind() fails.","code":"ErrorTypeBind ErrorType = 1 << 63"} {"repo":"gin","file":"errors.go","line":22,"symbol":"ErrorTypeRender","kind":"constant","lang":"go","doc":"ErrorTypeRender is used when Context.Render() fails.","code":"ErrorTypeRender ErrorType = 1 << 62"} {"repo":"gin","file":"errors.go","line":24,"symbol":"ErrorTypePrivate","kind":"constant","lang":"go","doc":"ErrorTypePrivate indicates a private error.","code":"ErrorTypePrivate ErrorType = 1 << 0"} {"repo":"gin","file":"errors.go","line":26,"symbol":"ErrorTypePublic","kind":"constant","lang":"go","doc":"ErrorTypePublic indicates a public error.","code":"ErrorTypePublic ErrorType = 1 << 1"} {"repo":"gin","file":"errors.go","line":28,"symbol":"ErrorTypeAny","kind":"constant","lang":"go","doc":"ErrorTypeAny indicates any other error.","code":"ErrorTypeAny ErrorType = 1<<64 - 1"} {"repo":"gin","file":"errors.go","line":32,"symbol":"Error","kind":"type","lang":"go","doc":"Error represents a error's specification.","code":"type Error struct {\n\tErr error\n\tType ErrorType\n\tMeta any\n}"} {"repo":"gin","file":"errors.go","line":38,"symbol":"errorMsgs","kind":"type","lang":"go","code":"type errorMsgs []*Error"} {"repo":"gin","file":"errors.go","line":40,"symbol":"_","kind":"variable","lang":"go","code":"_ error = (*Error)(nil)"} {"repo":"gin","file":"errors.go","line":43,"symbol":"SetType","kind":"method","lang":"go","doc":"SetType sets the error's type.","code":"func (msg *Error) SetType(flags ErrorType) *Error {\n\tmsg.Type = flags\n\treturn msg\n}"} {"repo":"gin","file":"errors.go","line":49,"symbol":"SetMeta","kind":"method","lang":"go","doc":"SetMeta sets the error's meta data.","code":"func (msg *Error) SetMeta(data any) *Error {\n\tmsg.Meta = data\n\treturn msg\n}"} {"repo":"gin","file":"errors.go","line":55,"symbol":"JSON","kind":"method","lang":"go","doc":"JSON creates a properly formatted JSON","code":"func (msg *Error) JSON() any {\n\tjsonData := H{}\n\tif msg.Meta != nil {\n\t\tvalue := reflect.ValueOf(msg.Meta)\n\t\tswitch value.Kind() {\n\t\tcase reflect.Struct:\n\t\t\treturn msg.Meta\n\t\tcase reflect.Map:\n\t\t\tfor _, key := range value.MapKeys() {\n\t\t\t\tjsonData[key.String()] = value.MapIndex(key).Interface()\n\t\t\t}\n\t\tdefault:\n\t\t\tjsonData[\"meta\"] = msg.Meta\n\t\t}\n\t}\n\tif _, ok := jsonData[\"error\"]; !ok {\n\t\tjsonData[\"error\"] = msg.Error()\n\t}\n\treturn jsonData\n}"} {"repo":"gin","file":"errors.go","line":77,"symbol":"MarshalJSON","kind":"method","lang":"go","doc":"MarshalJSON implements the json.Marshaller interface.","code":"func (msg *Error) MarshalJSON() ([]byte, error) {\n\treturn json.API.Marshal(msg.JSON())\n}"} {"repo":"gin","file":"errors.go","line":82,"symbol":"Error","kind":"method","lang":"go","doc":"Error implements the error interface.","code":"func (msg Error) Error() string {\n\treturn msg.Err.Error()\n}"} {"repo":"gin","file":"errors.go","line":87,"symbol":"IsType","kind":"method","lang":"go","doc":"IsType judges one error.","code":"func (msg *Error) IsType(flags ErrorType) bool {\n\treturn (msg.Type & flags) > 0\n}"} {"repo":"gin","file":"errors.go","line":92,"symbol":"Unwrap","kind":"method","lang":"go","doc":"Unwrap returns the wrapped error, to allow interoperability with errors.Is(), errors.As() and errors.Unwrap()","code":"func (msg Error) Unwrap() error {\n\treturn msg.Err\n}"} {"repo":"gin","file":"errors.go","line":98,"symbol":"ByType","kind":"method","lang":"go","doc":"ByType returns a readonly copy filtered the byte. ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic.","code":"func (a errorMsgs) ByType(typ ErrorType) errorMsgs {\n\tif len(a) == 0 {\n\t\treturn nil\n\t}\n\tif typ == ErrorTypeAny {\n\t\treturn a\n\t}\n\tvar result errorMsgs\n\tfor _, msg := range a {\n\t\tif msg.IsType(typ) {\n\t\t\tresult = append(result, msg)\n\t\t}\n\t}\n\treturn result\n}"} {"repo":"gin","file":"errors.go","line":105,"symbol":"result","kind":"variable","lang":"go","code":"result errorMsgs"} {"repo":"gin","file":"errors.go","line":116,"symbol":"Last","kind":"method","lang":"go","doc":"Last returns the last error in the slice. It returns nil if the array is empty. Shortcut for errors[len(errors)-1].","code":"func (a errorMsgs) Last() *Error {\n\tif length := len(a); length > 0 {\n\t\treturn a[length-1]\n\t}\n\treturn nil\n}"} {"repo":"gin","file":"errors.go","line":130,"symbol":"Errors","kind":"method","lang":"go","doc":"Example: c.Error(errors.New(\"first\")) c.Error(errors.New(\"second\")) c.Error(errors.New(\"third\")) c.Errors.Errors() // == []string{\"first\", \"second\", \"third\"}","code":"func (a errorMsgs) Errors() []string {\n\tif len(a) == 0 {\n\t\treturn nil\n\t}\n\terrorStrings := make([]string, len(a))\n\tfor i, err := range a {\n\t\terrorStrings[i] = err.Error()\n\t}\n\treturn errorStrings\n}"} {"repo":"gin","file":"errors.go","line":141,"symbol":"JSON","kind":"method","lang":"go","code":"func (a errorMsgs) JSON() any {\n\tswitch length := len(a); length {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\treturn a.Last().JSON()\n\tdefault:\n\t\tjsonData := make([]any, length)\n\t\tfor i, err := range a {\n\t\t\tjsonData[i] = err.JSON()\n\t\t}\n\t\treturn jsonData\n\t}\n}"} {"repo":"gin","file":"errors.go","line":157,"symbol":"MarshalJSON","kind":"method","lang":"go","doc":"MarshalJSON implements the json.Marshaller interface.","code":"func (a errorMsgs) MarshalJSON() ([]byte, error) {\n\treturn json.API.Marshal(a.JSON())\n}"} {"repo":"gin","file":"errors.go","line":161,"symbol":"String","kind":"method","lang":"go","code":"func (a errorMsgs) String() string {\n\tif len(a) == 0 {\n\t\treturn \"\"\n\t}\n\tvar buffer strings.Builder\n\tfor i, msg := range a {\n\t\tfmt.Fprintf(&buffer, \"Error #%02d: %s\\n\", i+1, msg.Err)\n\t\tif msg.Meta != nil {\n\t\t\tfmt.Fprintf(&buffer, \" Meta: %v\\n\", msg.Meta)\n\t\t}\n\t}\n\treturn buffer.String()\n}"} {"repo":"gin","file":"errors.go","line":165,"symbol":"buffer","kind":"variable","lang":"go","code":"buffer strings.Builder"} {"repo":"gin","file":"errors_test.go","line":17,"symbol":"TestError","kind":"function","lang":"go","code":"func TestError(t *testing.T) {\n\tbaseError := errors.New(\"test error\")\n\terr := &Error{\n\t\tErr: baseError,\n\t\tType: ErrorTypePrivate,\n\t}\n\tassert.Equal(t, err.Error(), baseError.Error())\n\tassert.Equal(t, H{\"error\": baseError.Error()}, err.JSON())\n\n\tassert.Equal(t, err.SetType(ErrorTypePublic), err)\n\tassert.Equal(t, ErrorTypePublic, err.Type)\n\n\tassert.Equal(t, err.SetMeta(\"some data\"), err)\n\tassert.Equal(t, \"some data\", err.Meta)\n\tassert.Equal(t, H{\n\t\t\"error\": baseError.Error(),\n\t\t\"meta\": \"some data\",\n\t}, err.JSON())\n\n\tjsonBytes, _ := json.API.Marshal(err)\n\tassert.JSONEq(t, \"{\\\"error\\\":\\\"test error\\\",\\\"meta\\\":\\\"some data\\\"}\", string(jsonBytes))\n\n\terr.SetMeta(H{ //nolint: errcheck\n\t\t\"status\": \"200\",\n\t\t\"data\": \"some data\",\n\t})\n\tassert.Equal(t, H{\n\t\t\"error\": baseError.Error(),\n\t\t\"status\": \"200\",\n\t\t\"data\": \"some data\",\n\t}, err.JSON())\n\n\terr.SetMeta(H{ //nolint: errcheck\n\t\t\"error\": \"custom error\",\n\t\t\"status\": \"200\",\n\t\t\"data\": \"some data\",\n\t})\n\tassert.Equal(t, H{\n\t\t\"error\": \"custom error\",\n\t\t\"status\": \"200\",\n\t\t\"data\": \"some data\",\n\t}, err.JSON())\n\n\ttype customError struct {\n\t\tstatus string\n\t\tdata string\n\t}\n\terr.SetMeta(customError{status: \"200\", data: \"other data\"}) //nolint: er"} {"repo":"gin","file":"errors_test.go","line":60,"symbol":"customError","kind":"type","lang":"go","code":"type customError struct {\n\t\tstatus string\n\t\tdata string\n\t}"} {"repo":"gin","file":"errors_test.go","line":68,"symbol":"TestErrorSlice","kind":"function","lang":"go","code":"func TestErrorSlice(t *testing.T) {\n\terrs := errorMsgs{\n\t\t{Err: errors.New(\"first\"), Type: ErrorTypePrivate},\n\t\t{Err: errors.New(\"second\"), Type: ErrorTypePrivate, Meta: \"some data\"},\n\t\t{Err: errors.New(\"third\"), Type: ErrorTypePublic, Meta: H{\"status\": \"400\"}},\n\t}\n\n\tassert.Equal(t, errs, errs.ByType(ErrorTypeAny))\n\tassert.Equal(t, \"third\", errs.Last().Error())\n\tassert.Equal(t, []string{\"first\", \"second\", \"third\"}, errs.Errors())\n\tassert.Equal(t, []string{\"third\"}, errs.ByType(ErrorTypePublic).Errors())\n\tassert.Equal(t, []string{\"first\", \"second\"}, errs.ByType(ErrorTypePrivate).Errors())\n\tassert.Equal(t, []string{\"first\", \"second\", \"third\"}, errs.ByType(ErrorTypePublic|ErrorTypePrivate).Errors())\n\tassert.Empty(t, errs.ByType(ErrorTypeBind))\n\tassert.Empty(t, errs.ByType(ErrorTypeBind).String())\n\n\tassert.Equal(t, `Error #01: first\nError #02: second\n Meta: some data\nError #03: third\n Meta: map[status:400]\n`, errs.String())\n\tassert.Equal(t, []any{\n\t\tH{\"error\": \"first\"},\n\t\tH{\"error\": \"second\", \"meta\": \"some data\"},\n\t\tH{\"error\": \"third\", \"status\": \"400\"},\n\t}, errs.JSON())\n\tjsonBytes, _ := json.API.Marshal(errs)\n\tassert.JSONEq(t, \"[{\\\"error\\\":\\\"first\\\"},{\\\"error\\\":\\\"second\\\",\\\"met"} {"repo":"gin","file":"errors_test.go","line":110,"symbol":"TestErr","kind":"type","lang":"go","code":"type TestErr string"} {"repo":"gin","file":"errors_test.go","line":112,"symbol":"Error","kind":"method","lang":"go","code":"func (e TestErr) Error() string { return string(e) }"} {"repo":"gin","file":"errors_test.go","line":116,"symbol":"TestErrorUnwrap","kind":"function","lang":"go","doc":"TestErrorUnwrap tests the behavior of gin.Error with \"errors.Is()\" and \"errors.As()\". \"errors.Is()\" and \"errors.As()\" have been added to the standard library in go 1.13.","code":"func TestErrorUnwrap(t *testing.T) {\n\tinnerErr := TestErr(\"some error\")\n\n\t// 2 layers of wrapping : use 'fmt.Errorf(\"%w\")' to wrap a gin.Error{}, which itself wraps innerErr\n\terr := fmt.Errorf(\"wrapped: %w\", &Error{\n\t\tErr: innerErr,\n\t\tType: ErrorTypeAny,\n\t})\n\n\t// check that 'errors.Is()' and 'errors.As()' behave as expected :\n\trequire.ErrorIs(t, err, innerErr)\n\tvar testErr TestErr\n\trequire.ErrorAs(t, err, &testErr)\n\n\t// Test non-pointer usage of gin.Error\n\terrNonPointer := Error{\n\t\tErr: innerErr,\n\t\tType: ErrorTypeAny,\n\t}\n\twrappedErr := fmt.Errorf(\"wrapped: %w\", errNonPointer)\n\t// Check that 'errors.Is()' and 'errors.As()' behave as expected for non-pointer usage\n\trequire.ErrorIs(t, wrappedErr, innerErr)\n\tvar testErrNonPointer TestErr\n\trequire.ErrorAs(t, wrappedErr, &testErrNonPointer)\n}"} {"repo":"gin","file":"errors_test.go","line":127,"symbol":"testErr","kind":"variable","lang":"go","code":"testErr TestErr"} {"repo":"gin","file":"errors_test.go","line":138,"symbol":"testErrNonPointer","kind":"variable","lang":"go","code":"testErrNonPointer TestErr"} {"repo":"gin","file":"fs.go","line":13,"symbol":"OnlyFilesFS","kind":"type","lang":"go","doc":"OnlyFilesFS implements an http.FileSystem without `Readdir` functionality.","code":"type OnlyFilesFS struct {\n\tFileSystem http.FileSystem\n}"} {"repo":"gin","file":"fs.go","line":18,"symbol":"Open","kind":"method","lang":"go","doc":"Open passes `Open` to the upstream implementation without `Readdir` functionality.","code":"func (o OnlyFilesFS) Open(name string) (http.File, error) {\n\tf, err := o.FileSystem.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn neutralizedReaddirFile{f}, nil\n}"} {"repo":"gin","file":"fs.go","line":28,"symbol":"neutralizedReaddirFile","kind":"type","lang":"go","doc":"neutralizedReaddirFile wraps http.File with a specific implementation of `Readdir`.","code":"type neutralizedReaddirFile struct {\n\thttp.File\n}"} {"repo":"gin","file":"fs.go","line":33,"symbol":"Readdir","kind":"method","lang":"go","doc":"Readdir overrides the http.File default implementation and always returns nil.","code":"func (n neutralizedReaddirFile) Readdir(_ int) ([]os.FileInfo, error) {\n\t// this disables directory listing\n\treturn nil, nil\n}"} {"repo":"gin","file":"fs.go","line":42,"symbol":"Dir","kind":"function","lang":"go","doc":"Dir returns an http.FileSystem that can be used by http.FileServer(). It is used internally in router.Static(). if listDirectory == true, then it works the same as http.Dir(), otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.","code":"func Dir(root string, listDirectory bool) http.FileSystem {\n\tfs := http.Dir(root)\n\n\tif listDirectory {\n\t\treturn fs\n\t}\n\n\treturn &OnlyFilesFS{FileSystem: fs}\n}"} {"repo":"gin","file":"fs_test.go","line":13,"symbol":"mockFileSystem","kind":"type","lang":"go","code":"type mockFileSystem struct {\n\topen func(name string) (http.File, error)\n}"} {"repo":"gin","file":"fs_test.go","line":17,"symbol":"Open","kind":"method","lang":"go","code":"func (m *mockFileSystem) Open(name string) (http.File, error) {\n\treturn m.open(name)\n}"} {"repo":"gin","file":"fs_test.go","line":21,"symbol":"TestOnlyFilesFS_Open","kind":"function","lang":"go","code":"func TestOnlyFilesFS_Open(t *testing.T) {\n\tvar testFile *os.File\n\tmockFS := &mockFileSystem{\n\t\topen: func(name string) (http.File, error) {\n\t\t\treturn testFile, nil\n\t\t},\n\t}\n\tfs := &OnlyFilesFS{FileSystem: mockFS}\n\n\tfile, err := fs.Open(\"foo\")\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, testFile, file.(neutralizedReaddirFile).File)\n}"} {"repo":"gin","file":"fs_test.go","line":22,"symbol":"testFile","kind":"variable","lang":"go","code":"testFile *os.File"} {"repo":"gin","file":"fs_test.go","line":36,"symbol":"TestOnlyFilesFS_Open_err","kind":"function","lang":"go","code":"func TestOnlyFilesFS_Open_err(t *testing.T) {\n\ttestError := errors.New(\"mock\")\n\tmockFS := &mockFileSystem{\n\t\topen: func(_ string) (http.File, error) {\n\t\t\treturn nil, testError\n\t\t},\n\t}\n\tfs := &OnlyFilesFS{FileSystem: mockFS}\n\n\tfile, err := fs.Open(\"foo\")\n\n\trequire.ErrorIs(t, err, testError)\n\tassert.Nil(t, file)\n}"} {"repo":"gin","file":"fs_test.go","line":51,"symbol":"Test_neuteredReaddirFile_Readdir","kind":"function","lang":"go","code":"func Test_neuteredReaddirFile_Readdir(t *testing.T) {\n\tn := neutralizedReaddirFile{}\n\n\tres, err := n.Readdir(0)\n\n\trequire.NoError(t, err)\n\tassert.Nil(t, res)\n}"} {"repo":"gin","file":"fs_test.go","line":60,"symbol":"TestDir_listDirectory","kind":"function","lang":"go","code":"func TestDir_listDirectory(t *testing.T) {\n\ttestRoot := \"foo\"\n\tfs := Dir(testRoot, true)\n\n\tassert.Equal(t, http.Dir(testRoot), fs)\n}"} {"repo":"gin","file":"fs_test.go","line":67,"symbol":"TestDir","kind":"function","lang":"go","code":"func TestDir(t *testing.T) {\n\ttestRoot := \"foo\"\n\tfs := Dir(testRoot, false)\n\n\tassert.Equal(t, &OnlyFilesFS{FileSystem: http.Dir(testRoot)}, fs)\n}"} {"repo":"gin","file":"gin.go","line":27,"symbol":"defaultMultipartMemory","kind":"constant","lang":"go","code":"defaultMultipartMemory = 32 << 20"} {"repo":"gin","file":"gin.go","line":28,"symbol":"escapedColon","kind":"constant","lang":"go","code":"escapedColon = \"\\\\:\""} {"repo":"gin","file":"gin.go","line":29,"symbol":"colon","kind":"constant","lang":"go","code":"colon = \":\""} {"repo":"gin","file":"gin.go","line":30,"symbol":"backslash","kind":"constant","lang":"go","code":"backslash = \"\\\\\""} {"repo":"gin","file":"gin.go","line":37,"symbol":"defaultReadHeaderTimeout","kind":"constant","lang":"go","doc":"defaultReadHeaderTimeout is the default ReadHeaderTimeout applied to the http.Server created by Run, RunTLS and RunListener. It protects against slowloris-style resource exhaustion when the caller does not configure a custom http.Server.","code":"defaultReadHeaderTimeout = 10 * time.Second"} {"repo":"gin","file":"gin.go","line":40,"symbol":"default404Body","kind":"variable","lang":"go","code":"default404Body = []byte(\"404 page not found\")"} {"repo":"gin","file":"gin.go","line":41,"symbol":"default405Body","kind":"variable","lang":"go","code":"default405Body = []byte(\"405 method not allowed\")"} {"repo":"gin","file":"gin.go","line":44,"symbol":"defaultPlatform","kind":"variable","lang":"go","code":"defaultPlatform string"} {"repo":"gin","file":"gin.go","line":46,"symbol":"defaultTrustedCIDRs","kind":"variable","lang":"go","code":"defaultTrustedCIDRs = []*net.IPNet{\n\t{ // 0.0.0.0/0 (IPv4)\n\t\tIP: net.IP{0x0, 0x0, 0x0, 0x0},\n\t\tMask: net.IPMask{0x0, 0x0, 0x0, 0x0},\n\t},\n\t{ // ::/0 (IPv6)\n\t\tIP: net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},\n\t\tMask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},\n\t},\n}"} {"repo":"gin","file":"gin.go","line":58,"symbol":"HandlerFunc","kind":"type","lang":"go","doc":"HandlerFunc defines the handler used by gin middleware as return value.","code":"type HandlerFunc func(*Context)"} {"repo":"gin","file":"gin.go","line":61,"symbol":"OptionFunc","kind":"type","lang":"go","doc":"OptionFunc defines the function to change the default configuration","code":"type OptionFunc func(*Engine)"} {"repo":"gin","file":"gin.go","line":64,"symbol":"HandlersChain","kind":"type","lang":"go","doc":"HandlersChain defines a HandlerFunc slice.","code":"type HandlersChain []HandlerFunc"} {"repo":"gin","file":"gin.go","line":67,"symbol":"Last","kind":"method","lang":"go","doc":"Last returns the last handler in the chain. i.e. the last handler is the main one.","code":"func (c HandlersChain) Last() HandlerFunc {\n\tif length := len(c); length > 0 {\n\t\treturn c[length-1]\n\t}\n\treturn nil\n}"} {"repo":"gin","file":"gin.go","line":75,"symbol":"RouteInfo","kind":"type","lang":"go","doc":"RouteInfo represents a request route's specification which contains method and path and its handler.","code":"type RouteInfo struct {\n\tMethod string\n\tPath string\n\tHandler string\n\tHandlerFunc HandlerFunc\n}"} {"repo":"gin","file":"gin.go","line":83,"symbol":"RoutesInfo","kind":"type","lang":"go","doc":"RoutesInfo defines a RouteInfo slice.","code":"type RoutesInfo []RouteInfo"} {"repo":"gin","file":"gin.go","line":89,"symbol":"PlatformGoogleAppEngine","kind":"constant","lang":"go","doc":"PlatformGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr for determining the client's IP","code":"PlatformGoogleAppEngine = \"X-Appengine-Remote-Addr\""} {"repo":"gin","file":"gin.go","line":92,"symbol":"PlatformCloudflare","kind":"constant","lang":"go","doc":"PlatformCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining the client's IP","code":"PlatformCloudflare = \"CF-Connecting-IP\""} {"repo":"gin","file":"gin.go","line":94,"symbol":"PlatformFlyIO","kind":"constant","lang":"go","doc":"PlatformFlyIO when running on Fly.io. Trust Fly-Client-IP for determining the client's IP","code":"PlatformFlyIO = \"Fly-Client-IP\""} {"repo":"gin","file":"gin.go","line":99,"symbol":"Engine","kind":"type","lang":"go","doc":"Engine is the framework's instance, it contains the muxer, middleware and configuration settings. Create an instance of Engine, by using New() or Default()","code":"type Engine struct {\n\tRouterGroup\n\n\t// routeTreesUpdated ensures that the initialization or update of the route trees\n\t// (used for routing HTTP requests) happens only once, even if called multiple times concurrently.\n\trouteTreesUpdated sync.Once\n\n\t// RedirectTrailingSlash enables automatic redirection if the current route can't be matched but a\n\t// handler for the path with (without) the trailing slash exists.\n\t// For example if /foo/ is requested but a route only exists for /foo, the\n\t// client is redirected to /foo with http status code 301 for GET requests\n\t// and 307 for all other request methods.\n\tRedirectTrailingSlash bool\n\n\t// RedirectFixedPath if enabled, the router tries to fix the current request path, if no\n\t// handle is registered for it.\n\t// First superfluous path elements like ../ or // are removed.\n\t// Afterwards the router does a case-insensitive lookup of the cleaned path.\n\t// If a handle can be found for this route, the router makes a redirection\n\t// to the corrected path with status code 301 for GET requests and 307 for\n\t// all other request methods.\n\t// For example /FOO and /..//Foo could be redirected to /foo.\n\t// RedirectTrailingSlash is independent of this o"} {"repo":"gin","file":"gin.go","line":204,"symbol":"_","kind":"variable","lang":"go","code":"_ IRouter = (*Engine)(nil)"} {"repo":"gin","file":"gin.go","line":215,"symbol":"New","kind":"function","lang":"go","doc":"- RedirectFixedPath: false - HandleMethodNotAllowed: false - ForwardedByClientIP: true - UseRawPath: false - UseEscapedPath: \t\t false - UnescapePathValues: true","code":"func New(opts ...OptionFunc) *Engine {\n\tdebugPrintWARNINGNew()\n\tengine := &Engine{\n\t\tRouterGroup: RouterGroup{\n\t\t\tHandlers: nil,\n\t\t\tbasePath: \"/\",\n\t\t\troot: true,\n\t\t},\n\t\tFuncMap: template.FuncMap{},\n\t\tRedirectTrailingSlash: true,\n\t\tRedirectFixedPath: false,\n\t\tHandleMethodNotAllowed: false,\n\t\tForwardedByClientIP: true,\n\t\tRemoteIPHeaders: []string{\"X-Forwarded-For\", \"X-Real-IP\"},\n\t\tTrustedPlatform: defaultPlatform,\n\t\tUseRawPath: false,\n\t\tUseEscapedPath: false,\n\t\tRemoveExtraSlash: false,\n\t\tUnescapePathValues: true,\n\t\tMaxMultipartMemory: defaultMultipartMemory,\n\t\tReadHeaderTimeout: defaultReadHeaderTimeout,\n\t\ttrees: make(methodTrees, 0, 9),\n\t\tdelims: render.Delims{Left: \"{{\", Right: \"}}\"},\n\t\tsecureJSONPrefix: \"while(1);\",\n\t\ttrustedProxies: []string{\"0.0.0.0/0\", \"::/0\"},\n\t\ttrustedCIDRs: defaultTrustedCIDRs,\n\t}\n\tengine.engine = engine\n\tengine.pool.New = func() any {\n\t\treturn engine.allocateContext(engine.maxParams)\n\t}\n\treturn engine.With(opts...)\n}"} {"repo":"gin","file":"gin.go","line":250,"symbol":"Default","kind":"function","lang":"go","doc":"Default returns an Engine instance with the Logger and Recovery middleware already attached.","code":"func Default(opts ...OptionFunc) *Engine {\n\tdebugPrintWARNINGDefault()\n\tengine := New()\n\tengine.Use(Logger(), Recovery())\n\treturn engine.With(opts...)\n}"} {"repo":"gin","file":"gin.go","line":257,"symbol":"Handler","kind":"method","lang":"go","code":"func (engine *Engine) Handler() http.Handler {\n\tif !engine.UseH2C {\n\t\treturn engine\n\t}\n\n\th2s := &http2.Server{}\n\treturn h2c.NewHandler(engine, h2s)\n}"} {"repo":"gin","file":"gin.go","line":266,"symbol":"allocateContext","kind":"method","lang":"go","code":"func (engine *Engine) allocateContext(maxParams uint16) *Context {\n\tv := make(Params, 0, maxParams)\n\tskippedNodes := make([]skippedNode, 0, engine.maxSections)\n\treturn &Context{engine: engine, params: &v, skippedNodes: &skippedNodes}\n}"} {"repo":"gin","file":"gin.go","line":274,"symbol":"getReadHeaderTimeout","kind":"method","lang":"go","doc":"getReadHeaderTimeout returns the configured ReadHeaderTimeout, or the default if it is zero or negative.","code":"func (engine *Engine) getReadHeaderTimeout() time.Duration {\n\tif engine.ReadHeaderTimeout <= 0 {\n\t\treturn defaultReadHeaderTimeout\n\t}\n\treturn engine.ReadHeaderTimeout\n}"} {"repo":"gin","file":"gin.go","line":282,"symbol":"Delims","kind":"method","lang":"go","doc":"Delims sets template left and right delims and returns an Engine instance.","code":"func (engine *Engine) Delims(left, right string) *Engine {\n\tengine.delims = render.Delims{Left: left, Right: right}\n\treturn engine\n}"} {"repo":"gin","file":"gin.go","line":288,"symbol":"SecureJsonPrefix","kind":"method","lang":"go","doc":"SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON.","code":"func (engine *Engine) SecureJsonPrefix(prefix string) *Engine {\n\tengine.secureJSONPrefix = prefix\n\treturn engine\n}"} {"repo":"gin","file":"gin.go","line":295,"symbol":"LoadHTMLGlob","kind":"method","lang":"go","doc":"LoadHTMLGlob loads HTML files identified by glob pattern and associates the result with HTML renderer.","code":"func (engine *Engine) LoadHTMLGlob(pattern string) {\n\tleft := engine.delims.Left\n\tright := engine.delims.Right\n\ttempl := template.Must(template.New(\"\").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern))\n\n\tif IsDebugging() {\n\t\tdebugPrintLoadTemplate(templ)\n\t\tengine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims}\n\t\treturn\n\t}\n\n\tengine.SetHTMLTemplate(templ)\n}"} {"repo":"gin","file":"gin.go","line":311,"symbol":"LoadHTMLFiles","kind":"method","lang":"go","doc":"LoadHTMLFiles loads a slice of HTML files and associates the result with HTML renderer.","code":"func (engine *Engine) LoadHTMLFiles(files ...string) {\n\tif IsDebugging() {\n\t\tengine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims}\n\t\treturn\n\t}\n\n\ttempl := template.Must(template.New(\"\").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...))\n\tengine.SetHTMLTemplate(templ)\n}"} {"repo":"gin","file":"gin.go","line":323,"symbol":"LoadHTMLFS","kind":"method","lang":"go","doc":"LoadHTMLFS loads an http.FileSystem and a slice of patterns and associates the result with HTML renderer.","code":"func (engine *Engine) LoadHTMLFS(fs http.FileSystem, patterns ...string) {\n\tif IsDebugging() {\n\t\tengine.HTMLRender = render.HTMLDebug{FileSystem: fs, Patterns: patterns, FuncMap: engine.FuncMap, Delims: engine.delims}\n\t\treturn\n\t}\n\n\ttempl := template.Must(template.New(\"\").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFS(\n\t\tfilesystem.FileSystem{FileSystem: fs}, patterns...))\n\tengine.SetHTMLTemplate(templ)\n}"} {"repo":"gin","file":"gin.go","line":335,"symbol":"SetHTMLTemplate","kind":"method","lang":"go","doc":"SetHTMLTemplate associate a template with HTML renderer.","code":"func (engine *Engine) SetHTMLTemplate(templ *template.Template) {\n\tif len(engine.trees) > 0 {\n\t\tdebugPrintWARNINGSetHTMLTemplate()\n\t}\n\n\tengine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)}\n}"} {"repo":"gin","file":"gin.go","line":344,"symbol":"SetFuncMap","kind":"method","lang":"go","doc":"SetFuncMap sets the FuncMap used for template.FuncMap.","code":"func (engine *Engine) SetFuncMap(funcMap template.FuncMap) {\n\tengine.FuncMap = funcMap\n}"} {"repo":"gin","file":"gin.go","line":349,"symbol":"NoRoute","kind":"method","lang":"go","doc":"NoRoute adds handlers for NoRoute. It returns a 404 code by default.","code":"func (engine *Engine) NoRoute(handlers ...HandlerFunc) {\n\tengine.noRoute = handlers\n\tengine.rebuild404Handlers()\n}"} {"repo":"gin","file":"gin.go","line":355,"symbol":"NoMethod","kind":"method","lang":"go","doc":"NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true.","code":"func (engine *Engine) NoMethod(handlers ...HandlerFunc) {\n\tengine.noMethod = handlers\n\tengine.rebuild405Handlers()\n}"} {"repo":"gin","file":"gin.go","line":363,"symbol":"Use","kind":"method","lang":"go","doc":"Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be included in the handlers chain for every single request. Even 404, 405, static files... For example, this is the right place for a logger or error management middleware.","code":"func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {\n\tengine.RouterGroup.Use(middleware...)\n\tengine.rebuild404Handlers()\n\tengine.rebuild405Handlers()\n\treturn engine\n}"} {"repo":"gin","file":"gin.go","line":371,"symbol":"With","kind":"method","lang":"go","doc":"With returns an Engine with the configuration set in the OptionFunc.","code":"func (engine *Engine) With(opts ...OptionFunc) *Engine {\n\tfor _, opt := range opts {\n\t\topt(engine)\n\t}\n\n\treturn engine\n}"} {"repo":"gin","file":"gin.go","line":379,"symbol":"rebuild404Handlers","kind":"method","lang":"go","code":"func (engine *Engine) rebuild404Handlers() {\n\tengine.allNoRoute = engine.combineHandlers(engine.noRoute)\n}"} {"repo":"gin","file":"gin.go","line":383,"symbol":"rebuild405Handlers","kind":"method","lang":"go","code":"func (engine *Engine) rebuild405Handlers() {\n\tengine.allNoMethod = engine.combineHandlers(engine.noMethod)\n}"} {"repo":"gin","file":"gin.go","line":387,"symbol":"addRoute","kind":"method","lang":"go","code":"func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {\n\tassert1(path[0] == '/', \"path must begin with '/'\")\n\tassert1(method != \"\", \"HTTP method can not be empty\")\n\tassert1(len(handlers) > 0, \"there must be at least one handler\")\n\n\tdebugPrintRoute(method, path, handlers)\n\n\troot := engine.trees.get(method)\n\tif root == nil {\n\t\troot = new(node)\n\t\troot.fullPath = \"/\"\n\t\tengine.trees = append(engine.trees, methodTree{method: method, root: root})\n\t}\n\troot.addRoute(path, handlers)\n\n\tif paramsCount := countParams(path); paramsCount > engine.maxParams {\n\t\tengine.maxParams = paramsCount\n\t}\n\n\tif sectionsCount := countSections(path); sectionsCount > engine.maxSections {\n\t\tengine.maxSections = sectionsCount\n\t}\n}"} {"repo":"gin","file":"gin.go","line":413,"symbol":"Routes","kind":"method","lang":"go","doc":"Routes returns a slice of registered routes, including some useful information, such as: the http method, path, and the handler name.","code":"func (engine *Engine) Routes() (routes RoutesInfo) {\n\tfor _, tree := range engine.trees {\n\t\troutes = iterate(\"\", tree.method, routes, tree.root)\n\t}\n\treturn routes\n}"} {"repo":"gin","file":"gin.go","line":420,"symbol":"iterate","kind":"function","lang":"go","code":"func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo {\n\tpath += root.path\n\tif len(root.handlers) > 0 {\n\t\thandlerFunc := root.handlers.Last()\n\t\troutes = append(routes, RouteInfo{\n\t\t\tMethod: method,\n\t\t\tPath: path,\n\t\t\tHandler: nameOfFunction(handlerFunc),\n\t\t\tHandlerFunc: handlerFunc,\n\t\t})\n\t}\n\tfor _, child := range root.children {\n\t\troutes = iterate(path, method, routes, child)\n\t}\n\treturn routes\n}"} {"repo":"gin","file":"gin.go","line":437,"symbol":"prepareTrustedCIDRs","kind":"method","lang":"go","code":"func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) {\n\tif engine.trustedProxies == nil {\n\t\treturn nil, nil\n\t}\n\n\tcidr := make([]*net.IPNet, 0, len(engine.trustedProxies))\n\tfor _, trustedProxy := range engine.trustedProxies {\n\t\tif !strings.Contains(trustedProxy, \"/\") {\n\t\t\tip := parseIP(trustedProxy)\n\t\t\tif ip == nil {\n\t\t\t\treturn cidr, &net.ParseError{Type: \"IP address\", Text: trustedProxy}\n\t\t\t}\n\n\t\t\tswitch len(ip) {\n\t\t\tcase net.IPv4len:\n\t\t\t\ttrustedProxy += \"/32\"\n\t\t\tcase net.IPv6len:\n\t\t\t\ttrustedProxy += \"/128\"\n\t\t\t}\n\t\t}\n\t\t_, cidrNet, err := net.ParseCIDR(trustedProxy)\n\t\tif err != nil {\n\t\t\treturn cidr, err\n\t\t}\n\t\tcidr = append(cidr, cidrNet)\n\t}\n\treturn cidr, nil\n}"} {"repo":"gin","file":"gin.go","line":474,"symbol":"SetTrustedProxies","kind":"method","lang":"go","doc":"request's headers that contain alternative client IP when `(*gin.Engine).ForwardedByClientIP` is `true`. `TrustedProxies` feature is enabled by default, and it also trusts all proxies by default. If you want to disable this feature, use Engine.SetTrustedProxies(nil), then Context.ClientIP() will return the remote address directly.","code":"func (engine *Engine) SetTrustedProxies(trustedProxies []string) error {\n\tengine.trustedProxies = trustedProxies\n\treturn engine.parseTrustedProxies()\n}"} {"repo":"gin","file":"gin.go","line":480,"symbol":"isUnsafeTrustedProxies","kind":"method","lang":"go","doc":"isUnsafeTrustedProxies checks if Engine.trustedCIDRs contains all IPs, it's not safe if it has (returns true)","code":"func (engine *Engine) isUnsafeTrustedProxies() bool {\n\treturn engine.isTrustedProxy(net.ParseIP(\"0.0.0.0\")) || engine.isTrustedProxy(net.ParseIP(\"::\"))\n}"} {"repo":"gin","file":"gin.go","line":485,"symbol":"parseTrustedProxies","kind":"method","lang":"go","doc":"parseTrustedProxies parse Engine.trustedProxies to Engine.trustedCIDRs","code":"func (engine *Engine) parseTrustedProxies() error {\n\ttrustedCIDRs, err := engine.prepareTrustedCIDRs()\n\tengine.trustedCIDRs = trustedCIDRs\n\treturn err\n}"} {"repo":"gin","file":"gin.go","line":492,"symbol":"isTrustedProxy","kind":"method","lang":"go","doc":"isTrustedProxy will check whether the IP address is included in the trusted list according to Engine.trustedCIDRs","code":"func (engine *Engine) isTrustedProxy(ip net.IP) bool {\n\tif engine.trustedCIDRs == nil {\n\t\treturn false\n\t}\n\tfor _, cidr := range engine.trustedCIDRs {\n\t\tif cidr.Contains(ip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"repo":"gin","file":"gin.go","line":505,"symbol":"validateHeader","kind":"method","lang":"go","doc":"validateHeader will parse X-Forwarded-For header and return the trusted client IP address","code":"func (engine *Engine) validateHeader(header string) (clientIP string, valid bool) {\n\tif header == \"\" {\n\t\treturn \"\", false\n\t}\n\titems := strings.Split(header, \",\")\n\tfor i := len(items) - 1; i >= 0; i-- {\n\t\tipStr := strings.TrimSpace(items[i])\n\t\tip := net.ParseIP(ipStr)\n\t\tif ip == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// X-Forwarded-For is appended by proxy\n\t\t// Check IPs in reverse order and stop when find untrusted proxy\n\t\tif (i == 0) || (!engine.isTrustedProxy(ip)) {\n\t\t\treturn ipStr, true\n\t\t}\n\t}\n\treturn \"\", false\n}"} {"repo":"gin","file":"gin.go","line":527,"symbol":"updateRouteTree","kind":"function","lang":"go","doc":"updateRouteTree do update to the route tree recursively","code":"func updateRouteTree(n *node) {\n\tn.path = strings.ReplaceAll(n.path, escapedColon, colon)\n\tn.fullPath = strings.ReplaceAll(n.fullPath, escapedColon, colon)\n\tn.indices = strings.ReplaceAll(n.indices, backslash, colon)\n\tif n.children == nil {\n\t\treturn\n\t}\n\tfor _, child := range n.children {\n\t\tupdateRouteTree(child)\n\t}\n}"} {"repo":"gin","file":"gin.go","line":540,"symbol":"updateRouteTrees","kind":"method","lang":"go","doc":"updateRouteTrees do update to the route trees","code":"func (engine *Engine) updateRouteTrees() {\n\tfor _, tree := range engine.trees {\n\t\tupdateRouteTree(tree.root)\n\t}\n}"} {"repo":"gin","file":"gin.go","line":548,"symbol":"parseIP","kind":"function","lang":"go","doc":"parseIP parse a string representation of an IP and returns a net.IP with the minimum byte representation or nil if input is invalid.","code":"func parseIP(ip string) net.IP {\n\tparsedIP := net.ParseIP(ip)\n\n\tif ipv4 := parsedIP.To4(); ipv4 != nil {\n\t\t// return ip in a 4-byte representation\n\t\treturn ipv4\n\t}\n\n\t// return ip in a 16-byte representation or nil\n\treturn parsedIP\n}"} {"repo":"gin","file":"gin.go","line":566,"symbol":"Run","kind":"method","lang":"go","doc":"Run attaches the router to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, router) Note: this method will block the calling goroutine indefinitely unless an error happens. The created http.Server is configured with a default ReadHeaderTimeout of 10 seconds (configurable via Engine.ReadHeaderTimeout) to mitigate slowloris attacks. For full control over timeouts, create a custom http.Server and use ServeHTTP.","code":"func (engine *Engine) Run(addr ...string) (err error) {\n\tdefer func() { debugPrintError(err) }()\n\n\tif engine.isUnsafeTrustedProxies() {\n\t\tdebugPrint(\"[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\\n\" +\n\t\t\t\"Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.\")\n\t}\n\tengine.updateRouteTrees()\n\taddress := resolveAddress(addr)\n\tdebugPrint(\"Listening and serving HTTP on %s\\n\", address)\n\tserver := &http.Server{ // #nosec G112\n\t\tAddr: address,\n\t\tHandler: engine.Handler(),\n\t\tReadHeaderTimeout: engine.getReadHeaderTimeout(),\n\t}\n\terr = server.ListenAndServe()\n\treturn\n}"} {"repo":"gin","file":"gin.go","line":588,"symbol":"RunTLS","kind":"method","lang":"go","doc":"RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) Note: this method will block the calling goroutine indefinitely unless an error happens.","code":"func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) {\n\tdebugPrint(\"Listening and serving HTTPS on %s\\n\", addr)\n\tdefer func() { debugPrintError(err) }()\n\n\tif engine.isUnsafeTrustedProxies() {\n\t\tdebugPrint(\"[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\\n\" +\n\t\t\t\"Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.\")\n\t}\n\n\tserver := &http.Server{ // #nosec G112\n\t\tAddr: addr,\n\t\tHandler: engine.Handler(),\n\t\tReadHeaderTimeout: engine.getReadHeaderTimeout(),\n\t}\n\terr = server.ListenAndServeTLS(certFile, keyFile)\n\treturn\n}"} {"repo":"gin","file":"gin.go","line":609,"symbol":"RunUnix","kind":"method","lang":"go","doc":"RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests through the specified unix socket (i.e. a file). Note: this method will block the calling goroutine indefinitely unless an error happens.","code":"func (engine *Engine) RunUnix(file string) (err error) {\n\tdebugPrint(\"Listening and serving HTTP on unix:/%s\", file)\n\tdefer func() { debugPrintError(err) }()\n\n\tif engine.isUnsafeTrustedProxies() {\n\t\tdebugPrint(\"[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\\n\" +\n\t\t\t\"Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.\")\n\t}\n\n\tlistener, err := net.Listen(\"unix\", file)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer listener.Close()\n\tdefer os.Remove(file)\n\n\tserver := &http.Server{ // #nosec G112\n\t\tHandler: engine.Handler(),\n\t}\n\terr = server.Serve(listener)\n\treturn\n}"} {"repo":"gin","file":"gin.go","line":635,"symbol":"RunFd","kind":"method","lang":"go","doc":"RunFd attaches the router to a http.Server and starts listening and serving HTTP requests through the specified file descriptor. Note: this method will block the calling goroutine indefinitely unless an error happens.","code":"func (engine *Engine) RunFd(fd int) (err error) {\n\tdebugPrint(\"Listening and serving HTTP on fd@%d\", fd)\n\tdefer func() { debugPrintError(err) }()\n\n\tif engine.isUnsafeTrustedProxies() {\n\t\tdebugPrint(\"[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\\n\" +\n\t\t\t\"Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.\")\n\t}\n\n\tf := os.NewFile(uintptr(fd), fmt.Sprintf(\"fd@%d\", fd))\n\tdefer f.Close()\n\tlistener, err := net.FileListener(f)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer listener.Close()\n\terr = engine.RunListener(listener)\n\treturn\n}"} {"repo":"gin","file":"gin.go","line":658,"symbol":"RunQUIC","kind":"method","lang":"go","doc":"RunQUIC attaches the router to a http.Server and starts listening and serving QUIC requests. It is a shortcut for http3.ListenAndServeQUIC(addr, certFile, keyFile, router) Note: this method will block the calling goroutine indefinitely unless an error happens.","code":"func (engine *Engine) RunQUIC(addr, certFile, keyFile string) (err error) {\n\tdebugPrint(\"Listening and serving QUIC on %s\\n\", addr)\n\tdefer func() { debugPrintError(err) }()\n\n\tif engine.isUnsafeTrustedProxies() {\n\t\tdebugPrint(\"[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\\n\" +\n\t\t\t\"Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.\")\n\t}\n\n\terr = http3.ListenAndServeQUIC(addr, certFile, keyFile, engine.Handler())\n\treturn\n}"} {"repo":"gin","file":"gin.go","line":673,"symbol":"RunListener","kind":"method","lang":"go","doc":"RunListener attaches the router to a http.Server and starts listening and serving HTTP requests through the specified net.Listener","code":"func (engine *Engine) RunListener(listener net.Listener) (err error) {\n\tdebugPrint(\"Listening and serving HTTP on listener what's bind with address@%s\", listener.Addr())\n\tdefer func() { debugPrintError(err) }()\n\n\tif engine.isUnsafeTrustedProxies() {\n\t\tdebugPrint(\"[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\\n\" +\n\t\t\t\"Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.\")\n\t}\n\n\tserver := &http.Server{ // #nosec G112\n\t\tHandler: engine.Handler(),\n\t\tReadHeaderTimeout: engine.getReadHeaderTimeout(),\n\t}\n\terr = server.Serve(listener)\n\treturn\n}"} {"repo":"gin","file":"gin.go","line":691,"symbol":"ServeHTTP","kind":"method","lang":"go","doc":"ServeHTTP conforms to the http.Handler interface.","code":"func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tengine.routeTreesUpdated.Do(func() {\n\t\tengine.updateRouteTrees()\n\t})\n\n\tc := engine.pool.Get().(*Context)\n\tc.writermem.reset(w)\n\tc.Request = req\n\tc.reset()\n\n\tengine.handleHTTPRequest(c)\n\n\tengine.pool.Put(c)\n}"} {"repo":"gin","file":"gin.go","line":709,"symbol":"HandleContext","kind":"method","lang":"go","doc":"HandleContext re-enters a context that has been rewritten. This can be done by setting c.Request.URL.Path to your new target. Disclaimer: You can loop yourself to deal with this, use wisely.","code":"func (engine *Engine) HandleContext(c *Context) {\n\toldIndexValue := c.index\n\toldHandlers := c.handlers\n\tc.reset()\n\tengine.handleHTTPRequest(c)\n\n\tc.index = oldIndexValue\n\tc.handlers = oldHandlers\n}"} {"repo":"gin","file":"gin.go","line":719,"symbol":"handleHTTPRequest","kind":"method","lang":"go","code":"func (engine *Engine) handleHTTPRequest(c *Context) {\n\thttpMethod := c.Request.Method\n\trPath := c.Request.URL.Path\n\tunescape := false\n\n\tif engine.UseEscapedPath {\n\t\trPath = c.Request.URL.EscapedPath()\n\t\tunescape = engine.UnescapePathValues\n\t} else if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {\n\t\trPath = c.Request.URL.RawPath\n\t\tunescape = engine.UnescapePathValues\n\t}\n\n\tif engine.RemoveExtraSlash {\n\t\trPath = cleanPath(rPath)\n\t}\n\n\t// Find root of the tree for the given HTTP method\n\tt := engine.trees\n\tfor i, tl := 0, len(t); i < tl; i++ {\n\t\tif t[i].method != httpMethod {\n\t\t\tcontinue\n\t\t}\n\t\troot := t[i].root\n\t\t// Find route in tree\n\t\tvalue := root.getValue(rPath, c.params, c.skippedNodes, unescape)\n\t\tif value.params != nil {\n\t\t\tc.Params = *value.params\n\t\t}\n\t\tif value.handlers != nil {\n\t\t\tc.handlers = value.handlers\n\t\t\tc.fullPath = value.fullPath\n\t\t\tc.Next()\n\t\t\tc.writermem.WriteHeaderNow()\n\t\t\treturn\n\t\t}\n\t\tif httpMethod != http.MethodConnect && rPath != \"/\" {\n\t\t\tif value.tsr && engine.RedirectTrailingSlash {\n\t\t\t\tredirectTrailingSlash(c)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\tif engi"} {"repo":"gin","file":"gin.go","line":791,"symbol":"mimePlain","kind":"variable","lang":"go","code":"mimePlain = []string{MIMEPlain}"} {"repo":"gin","file":"ginS/gins.go","line":15,"symbol":"engine","kind":"variable","lang":"go","code":"engine = sync.OnceValue(func() *gin.Engine {\n\treturn gin.Default()\n})"} {"repo":"gin","file":"ginS/gins.go","line":20,"symbol":"LoadHTMLGlob","kind":"function","lang":"go","doc":"LoadHTMLGlob is a wrapper for Engine.LoadHTMLGlob.","code":"func LoadHTMLGlob(pattern string) {\n\tengine().LoadHTMLGlob(pattern)\n}"} {"repo":"gin","file":"ginS/gins.go","line":25,"symbol":"LoadHTMLFiles","kind":"function","lang":"go","doc":"LoadHTMLFiles is a wrapper for Engine.LoadHTMLFiles.","code":"func LoadHTMLFiles(files ...string) {\n\tengine().LoadHTMLFiles(files...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":30,"symbol":"LoadHTMLFS","kind":"function","lang":"go","doc":"LoadHTMLFS is a wrapper for Engine.LoadHTMLFS.","code":"func LoadHTMLFS(fs http.FileSystem, patterns ...string) {\n\tengine().LoadHTMLFS(fs, patterns...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":35,"symbol":"SetHTMLTemplate","kind":"function","lang":"go","doc":"SetHTMLTemplate is a wrapper for Engine.SetHTMLTemplate.","code":"func SetHTMLTemplate(templ *template.Template) {\n\tengine().SetHTMLTemplate(templ)\n}"} {"repo":"gin","file":"ginS/gins.go","line":40,"symbol":"NoRoute","kind":"function","lang":"go","doc":"NoRoute adds handlers for NoRoute. It returns a 404 code by default.","code":"func NoRoute(handlers ...gin.HandlerFunc) {\n\tengine().NoRoute(handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":45,"symbol":"NoMethod","kind":"function","lang":"go","doc":"NoMethod is a wrapper for Engine.NoMethod.","code":"func NoMethod(handlers ...gin.HandlerFunc) {\n\tengine().NoMethod(handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":51,"symbol":"Group","kind":"function","lang":"go","doc":"Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. For example, all the routes that use a common middleware for authorization could be grouped.","code":"func Group(relativePath string, handlers ...gin.HandlerFunc) *gin.RouterGroup {\n\treturn engine().Group(relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":56,"symbol":"Handle","kind":"function","lang":"go","doc":"Handle is a wrapper for Engine.Handle.","code":"func Handle(httpMethod, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().Handle(httpMethod, relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":61,"symbol":"POST","kind":"function","lang":"go","doc":"POST is a shortcut for router.Handle(\"POST\", path, handle)","code":"func POST(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().POST(relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":66,"symbol":"GET","kind":"function","lang":"go","doc":"GET is a shortcut for router.Handle(\"GET\", path, handle)","code":"func GET(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().GET(relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":71,"symbol":"QUERY","kind":"function","lang":"go","doc":"QUERY is a shortcut for router.Handle(\"QUERY\", path, handle)","code":"func QUERY(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().QUERY(relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":76,"symbol":"DELETE","kind":"function","lang":"go","doc":"DELETE is a shortcut for router.Handle(\"DELETE\", path, handle)","code":"func DELETE(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().DELETE(relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":81,"symbol":"PATCH","kind":"function","lang":"go","doc":"PATCH is a shortcut for router.Handle(\"PATCH\", path, handle)","code":"func PATCH(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().PATCH(relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":86,"symbol":"PUT","kind":"function","lang":"go","doc":"PUT is a shortcut for router.Handle(\"PUT\", path, handle)","code":"func PUT(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().PUT(relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":91,"symbol":"OPTIONS","kind":"function","lang":"go","doc":"OPTIONS is a shortcut for router.Handle(\"OPTIONS\", path, handle)","code":"func OPTIONS(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().OPTIONS(relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":96,"symbol":"HEAD","kind":"function","lang":"go","doc":"HEAD is a shortcut for router.Handle(\"HEAD\", path, handle)","code":"func HEAD(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().HEAD(relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":101,"symbol":"Any","kind":"function","lang":"go","doc":"Any is a wrapper for Engine.Any.","code":"func Any(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().Any(relativePath, handlers...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":106,"symbol":"StaticFile","kind":"function","lang":"go","doc":"StaticFile is a wrapper for Engine.StaticFile.","code":"func StaticFile(relativePath, filepath string) gin.IRoutes {\n\treturn engine().StaticFile(relativePath, filepath)\n}"} {"repo":"gin","file":"ginS/gins.go","line":117,"symbol":"Static","kind":"function","lang":"go","doc":"Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use : router.Static(\"/static\", \"/var/www\")","code":"func Static(relativePath, root string) gin.IRoutes {\n\treturn engine().Static(relativePath, root)\n}"} {"repo":"gin","file":"ginS/gins.go","line":122,"symbol":"StaticFS","kind":"function","lang":"go","doc":"StaticFS is a wrapper for Engine.StaticFS.","code":"func StaticFS(relativePath string, fs http.FileSystem) gin.IRoutes {\n\treturn engine().StaticFS(relativePath, fs)\n}"} {"repo":"gin","file":"ginS/gins.go","line":129,"symbol":"Use","kind":"function","lang":"go","doc":"Use attaches a global middleware to the router. i.e. the middlewares attached through Use() will be included in the handlers chain for every single request. Even 404, 405, static files... For example, this is the right place for a logger or error management middleware.","code":"func Use(middlewares ...gin.HandlerFunc) gin.IRoutes {\n\treturn engine().Use(middlewares...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":134,"symbol":"Routes","kind":"function","lang":"go","doc":"Routes returns a slice of registered routes.","code":"func Routes() gin.RoutesInfo {\n\treturn engine().Routes()\n}"} {"repo":"gin","file":"ginS/gins.go","line":141,"symbol":"Run","kind":"function","lang":"go","doc":"Run attaches to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, router) Note: this method will block the calling goroutine indefinitely unless an error happens.","code":"func Run(addr ...string) (err error) {\n\treturn engine().Run(addr...)\n}"} {"repo":"gin","file":"ginS/gins.go","line":148,"symbol":"RunTLS","kind":"function","lang":"go","doc":"RunTLS attaches to a http.Server and starts listening and serving HTTPS requests. It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) Note: this method will block the calling goroutine indefinitely unless an error happens.","code":"func RunTLS(addr, certFile, keyFile string) (err error) {\n\treturn engine().RunTLS(addr, certFile, keyFile)\n}"} {"repo":"gin","file":"ginS/gins.go","line":155,"symbol":"RunUnix","kind":"function","lang":"go","doc":"RunUnix attaches to a http.Server and starts listening and serving HTTP requests through the specified unix socket (i.e. a file) Note: this method will block the calling goroutine indefinitely unless an error happens.","code":"func RunUnix(file string) (err error) {\n\treturn engine().RunUnix(file)\n}"} {"repo":"gin","file":"ginS/gins.go","line":162,"symbol":"RunFd","kind":"function","lang":"go","doc":"RunFd attaches the router to a http.Server and starts listening and serving HTTP requests through the specified file descriptor. Note: the method will block the calling goroutine indefinitely unless an error happens.","code":"func RunFd(fd int) (err error) {\n\treturn engine().RunFd(fd)\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":17,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tgin.SetMode(gin.TestMode)\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":21,"symbol":"TestGET","kind":"function","lang":"go","code":"func TestGET(t *testing.T) {\n\tGET(\"/test\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"test\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodGet, \"/test\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"test\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":34,"symbol":"TestQUERY","kind":"function","lang":"go","code":"func TestQUERY(t *testing.T) {\n\tQUERY(\"/query\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"query\")\n\t})\n\n\treq := httptest.NewRequest(gin.MethodQuery, \"/query\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"query\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":47,"symbol":"TestPOST","kind":"function","lang":"go","code":"func TestPOST(t *testing.T) {\n\tPOST(\"/post\", func(c *gin.Context) {\n\t\tc.String(http.StatusCreated, \"created\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodPost, \"/post\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusCreated, w.Code)\n\tassert.Equal(t, \"created\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":60,"symbol":"TestPUT","kind":"function","lang":"go","code":"func TestPUT(t *testing.T) {\n\tPUT(\"/put\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"updated\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodPut, \"/put\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"updated\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":73,"symbol":"TestDELETE","kind":"function","lang":"go","code":"func TestDELETE(t *testing.T) {\n\tDELETE(\"/delete\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"deleted\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodDelete, \"/delete\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"deleted\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":86,"symbol":"TestPATCH","kind":"function","lang":"go","code":"func TestPATCH(t *testing.T) {\n\tPATCH(\"/patch\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"patched\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodPatch, \"/patch\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"patched\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":99,"symbol":"TestOPTIONS","kind":"function","lang":"go","code":"func TestOPTIONS(t *testing.T) {\n\tOPTIONS(\"/options\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"options\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodOptions, \"/options\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"options\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":112,"symbol":"TestHEAD","kind":"function","lang":"go","code":"func TestHEAD(t *testing.T) {\n\tHEAD(\"/head\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"head\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodHead, \"/head\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":124,"symbol":"TestAny","kind":"function","lang":"go","code":"func TestAny(t *testing.T) {\n\tAny(\"/any\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"any\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodGet, \"/any\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"any\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":137,"symbol":"TestHandle","kind":"function","lang":"go","code":"func TestHandle(t *testing.T) {\n\tHandle(http.MethodGet, \"/handle\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"handle\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodGet, \"/handle\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"handle\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":150,"symbol":"TestGroup","kind":"function","lang":"go","code":"func TestGroup(t *testing.T) {\n\tgroup := Group(\"/group\")\n\tgroup.GET(\"/test\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"group test\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodGet, \"/group/test\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"group test\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":164,"symbol":"TestUse","kind":"function","lang":"go","code":"func TestUse(t *testing.T) {\n\tvar middlewareExecuted bool\n\tUse(func(c *gin.Context) {\n\t\tmiddlewareExecuted = true\n\t\tc.Next()\n\t})\n\n\tGET(\"/middleware-test\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"ok\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodGet, \"/middleware-test\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.True(t, middlewareExecuted)\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":165,"symbol":"middlewareExecuted","kind":"variable","lang":"go","code":"middlewareExecuted bool"} {"repo":"gin","file":"ginS/gins_test.go","line":183,"symbol":"TestNoRoute","kind":"function","lang":"go","code":"func TestNoRoute(t *testing.T) {\n\tNoRoute(func(c *gin.Context) {\n\t\tc.String(http.StatusNotFound, \"custom 404\")\n\t})\n\n\treq := httptest.NewRequest(http.MethodGet, \"/nonexistent\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n\tassert.Equal(t, \"custom 404\", w.Body.String())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":196,"symbol":"TestNoMethod","kind":"function","lang":"go","code":"func TestNoMethod(t *testing.T) {\n\tNoMethod(func(c *gin.Context) {\n\t\tc.String(http.StatusMethodNotAllowed, \"method not allowed\")\n\t})\n\n\t// This just verifies that NoMethod is callable\n\t// Testing the actual behavior would require a separate engine instance\n\tassert.NotNil(t, engine())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":206,"symbol":"TestRoutes","kind":"function","lang":"go","code":"func TestRoutes(t *testing.T) {\n\tGET(\"/routes-test\", func(c *gin.Context) {})\n\n\troutes := Routes()\n\tassert.NotEmpty(t, routes)\n\n\tfound := false\n\tfor _, route := range routes {\n\t\tif route.Path == \"/routes-test\" && route.Method == http.MethodGet {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.True(t, found)\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":222,"symbol":"TestSetHTMLTemplate","kind":"function","lang":"go","code":"func TestSetHTMLTemplate(t *testing.T) {\n\ttmpl := template.Must(template.New(\"test\").Parse(\"Hello {{.}}\"))\n\tSetHTMLTemplate(tmpl)\n\n\t// Verify engine has template set\n\tassert.NotNil(t, engine())\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":230,"symbol":"TestStaticFile","kind":"function","lang":"go","code":"func TestStaticFile(t *testing.T) {\n\tStaticFile(\"/static-file\", \"../testdata/test_file.txt\")\n\n\treq := httptest.NewRequest(http.MethodGet, \"/static-file\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":240,"symbol":"TestStatic","kind":"function","lang":"go","code":"func TestStatic(t *testing.T) {\n\tStatic(\"/static-dir\", \"../testdata\")\n\n\treq := httptest.NewRequest(http.MethodGet, \"/static-dir/test_file.txt\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"repo":"gin","file":"ginS/gins_test.go","line":250,"symbol":"TestStaticFS","kind":"function","lang":"go","code":"func TestStaticFS(t *testing.T) {\n\tfs := http.Dir(\"../testdata\")\n\tStaticFS(\"/static-fs\", fs)\n\n\treq := httptest.NewRequest(http.MethodGet, \"/static-fs/test_file.txt\", nil)\n\tw := httptest.NewRecorder()\n\tengine().ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"repo":"gin","file":"gin_integration_test.go","line":32,"symbol":"testRequest","kind":"function","lang":"go","doc":"testRequest sends a request and validates its response. params[0]=url example:http://127.0.0.1:8080/index (cannot be empty) params[1]=response status (custom compare status) default:\"200 OK\" params[2]=response body (custom compare content) default:\"it worked\"","code":"func testRequest(t *testing.T, params ...string) {\n\tif len(params) == 0 {\n\t\tt.Fatal(\"url cannot be empty\")\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\tresp, err := client.Get(params[0])\n\trequire.NoError(t, err)\n\tdefer resp.Body.Close()\n\n\tbody, ioerr := io.ReadAll(resp.Body)\n\trequire.NoError(t, ioerr)\n\n\tresponseStatus := \"200 OK\"\n\tif len(params) > 1 && params[1] != \"\" {\n\t\tresponseStatus = params[1]\n\t}\n\n\tresponseBody := \"it worked\"\n\tif len(params) > 2 && params[2] != \"\" {\n\t\tresponseBody = params[2]\n\t}\n\n\tassert.Equal(t, responseStatus, resp.Status, \"should get a \"+responseStatus)\n\tif responseStatus == \"200 OK\" {\n\t\tassert.Equal(t, responseBody, string(body), \"resp body should match\")\n\t}\n}"} {"repo":"gin","file":"gin_integration_test.go","line":67,"symbol":"TestRunEmpty","kind":"function","lang":"go","code":"func TestRunEmpty(t *testing.T) {\n\tos.Setenv(\"PORT\", \"\")\n\trouter := New()\n\tgo func() {\n\t\trouter.GET(\"/example\", func(c *Context) { c.String(http.StatusOK, \"it worked\") })\n\t\tassert.NoError(t, router.Run())\n\t}()\n\n\t// Wait for server to be ready with exponential backoff\n\terr := waitForServerReady(\"http://localhost:8080/example\", 10)\n\trequire.NoError(t, err, \"server should start successfully\")\n\n\trequire.Error(t, router.Run(\":8080\"))\n\ttestRequest(t, \"http://localhost:8080/example\")\n}"} {"repo":"gin","file":"gin_integration_test.go","line":83,"symbol":"TestBadTrustedCIDRs","kind":"function","lang":"go","code":"func TestBadTrustedCIDRs(t *testing.T) {\n\trouter := New()\n\trequire.Error(t, router.SetTrustedProxies([]string{\"hello/world\"}))\n}"} {"repo":"gin","file":"gin_integration_test.go","line":158,"symbol":"TestRunTLS","kind":"function","lang":"go","code":"func TestRunTLS(t *testing.T) {\n\trouter := New()\n\tgo func() {\n\t\trouter.GET(\"/example\", func(c *Context) { c.String(http.StatusOK, \"it worked\") })\n\n\t\tassert.NoError(t, router.RunTLS(\":8443\", \"./testdata/certificate/cert.pem\", \"./testdata/certificate/key.pem\"))\n\t}()\n\n\t// have to wait for the goroutine to start and run the server\n\t// otherwise the main thread will complete\n\ttime.Sleep(5 * time.Millisecond)\n\n\trequire.Error(t, router.RunTLS(\":8443\", \"./testdata/certificate/cert.pem\", \"./testdata/certificate/key.pem\"))\n\ttestRequest(t, \"https://localhost:8443/example\")\n}"} {"repo":"gin","file":"gin_integration_test.go","line":174,"symbol":"TestPusher","kind":"function","lang":"go","code":"func TestPusher(t *testing.T) {\n\thtml := template.Must(template.New(\"https\").Parse(`\n\n\n Https Test\n \n\n\n

Welcome, Ginner!

\n\n\n`))\n\n\trouter := New()\n\trouter.Static(\"./assets\", \"./assets\")\n\trouter.SetHTMLTemplate(html)\n\n\tgo func() {\n\t\trouter.GET(\"/pusher\", func(c *Context) {\n\t\t\tif pusher := c.Writer.Pusher(); pusher != nil {\n\t\t\t\terr := pusher.Push(\"/assets/app.js\", nil)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\t\t\tc.String(http.StatusOK, \"it worked\")\n\t\t})\n\n\t\tassert.NoError(t, router.RunTLS(\":8449\", \"./testdata/certificate/cert.pem\", \"./testdata/certificate/key.pem\"))\n\t}()\n\n\t// have to wait for the goroutine to start and run the server\n\t// otherwise the main thread will complete\n\ttime.Sleep(5 * time.Millisecond)\n\n\trequire.Error(t, router.RunTLS(\":8449\", \"./testdata/certificate/cert.pem\", \"./testdata/certificate/key.pem\"))\n\ttestRequest(t, \"https://localhost:8449/pusher\")\n}"} {"repo":"gin","file":"gin_integration_test.go","line":211,"symbol":"TestRunEmptyWithEnv","kind":"function","lang":"go","code":"func TestRunEmptyWithEnv(t *testing.T) {\n\tos.Setenv(\"PORT\", \"3123\")\n\trouter := New()\n\tgo func() {\n\t\trouter.GET(\"/example\", func(c *Context) { c.String(http.StatusOK, \"it worked\") })\n\t\tassert.NoError(t, router.Run())\n\t}()\n\n\t// Wait for server to be ready with exponential backoff\n\terr := waitForServerReady(\"http://localhost:3123/example\", 10)\n\trequire.NoError(t, err, \"server should start successfully\")\n\n\trequire.Error(t, router.Run(\":3123\"))\n\ttestRequest(t, \"http://localhost:3123/example\")\n}"} {"repo":"gin","file":"gin_integration_test.go","line":227,"symbol":"TestRunTooMuchParams","kind":"function","lang":"go","code":"func TestRunTooMuchParams(t *testing.T) {\n\trouter := New()\n\tassert.Panics(t, func() {\n\t\trequire.NoError(t, router.Run(\"2\", \"2\"))\n\t})\n}"} {"repo":"gin","file":"gin_integration_test.go","line":234,"symbol":"TestRunWithPort","kind":"function","lang":"go","code":"func TestRunWithPort(t *testing.T) {\n\trouter := New()\n\tgo func() {\n\t\trouter.GET(\"/example\", func(c *Context) { c.String(http.StatusOK, \"it worked\") })\n\t\tassert.NoError(t, router.Run(\":5150\"))\n\t}()\n\n\t// Wait for server to be ready with exponential backoff\n\terr := waitForServerReady(\"http://localhost:5150/example\", 10)\n\trequire.NoError(t, err, \"server should start successfully\")\n\n\trequire.Error(t, router.Run(\":5150\"))\n\ttestRequest(t, \"http://localhost:5150/example\")\n}"} {"repo":"gin","file":"gin_integration_test.go","line":249,"symbol":"TestUnixSocket","kind":"function","lang":"go","code":"func TestUnixSocket(t *testing.T) {\n\trouter := New()\n\n\tunixTestSocket := filepath.Join(os.TempDir(), \"unix_unit_test\")\n\n\tdefer os.Remove(unixTestSocket)\n\n\tgo func() {\n\t\trouter.GET(\"/example\", func(c *Context) { c.String(http.StatusOK, \"it worked\") })\n\t\tassert.NoError(t, router.RunUnix(unixTestSocket))\n\t}()\n\t// have to wait for the goroutine to start and run the server\n\t// otherwise the main thread will complete\n\ttime.Sleep(5 * time.Millisecond)\n\n\tc, err := net.Dial(\"unix\", unixTestSocket)\n\trequire.NoError(t, err)\n\n\tfmt.Fprint(c, \"GET /example HTTP/1.0\\r\\n\\r\\n\")\n\tscanner := bufio.NewScanner(c)\n\tvar responseBuilder strings.Builder\n\tfor scanner.Scan() {\n\t\tresponseBuilder.WriteString(scanner.Text())\n\t}\n\tresponse := responseBuilder.String()\n\tassert.Contains(t, response, \"HTTP/1.0 200\", \"should get a 200\")\n\tassert.Contains(t, response, \"it worked\", \"resp body should match\")\n}"} {"repo":"gin","file":"gin_integration_test.go","line":269,"symbol":"responseBuilder","kind":"variable","lang":"go","code":"responseBuilder strings.Builder"} {"repo":"gin","file":"gin_integration_test.go","line":278,"symbol":"TestBadUnixSocket","kind":"function","lang":"go","code":"func TestBadUnixSocket(t *testing.T) {\n\trouter := New()\n\trequire.Error(t, router.RunUnix(\"#/tmp/unix_unit_test\"))\n}"} {"repo":"gin","file":"gin_integration_test.go","line":283,"symbol":"TestRunQUIC","kind":"function","lang":"go","code":"func TestRunQUIC(t *testing.T) {\n\trouter := New()\n\tgo func() {\n\t\trouter.GET(\"/example\", func(c *Context) { c.String(http.StatusOK, \"it worked\") })\n\n\t\tassert.NoError(t, router.RunQUIC(\":8443\", \"./testdata/certificate/cert.pem\", \"./testdata/certificate/key.pem\"))\n\t}()\n\n\t// have to wait for the goroutine to start and run the server\n\t// otherwise the main thread will complete\n\ttime.Sleep(5 * time.Millisecond)\n\n\trequire.Error(t, router.RunQUIC(\":8443\", \"./testdata/certificate/cert.pem\", \"./testdata/certificate/key.pem\"))\n\ttestRequest(t, \"https://localhost:8443/example\")\n}"} {"repo":"gin","file":"gin_integration_test.go","line":299,"symbol":"TestFileDescriptor","kind":"function","lang":"go","code":"func TestFileDescriptor(t *testing.T) {\n\trouter := New()\n\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\trequire.NoError(t, err)\n\tlistener, err := net.ListenTCP(\"tcp\", addr)\n\trequire.NoError(t, err)\n\tsocketFile, err := listener.File()\n\tif isWindows() {\n\t\t// not supported by windows, it is unimplemented now\n\t\trequire.Error(t, err)\n\t} else {\n\t\trequire.NoError(t, err)\n\t}\n\n\tif socketFile == nil {\n\t\treturn\n\t}\n\n\tgo func() {\n\t\trouter.GET(\"/example\", func(c *Context) { c.String(http.StatusOK, \"it worked\") })\n\t\tassert.NoError(t, router.RunFd(int(socketFile.Fd())))\n\t}()\n\t// have to wait for the goroutine to start and run the server\n\t// otherwise the main thread will complete\n\ttime.Sleep(5 * time.Millisecond)\n\n\tc, err := net.Dial(\"tcp\", listener.Addr().String())\n\trequire.NoError(t, err)\n\n\tfmt.Fprintf(c, \"GET /example HTTP/1.0\\r\\n\\r\\n\")\n\tscanner := bufio.NewScanner(c)\n\tvar responseBuilder strings.Builder\n\tfor scanner.Scan() {\n\t\tresponseBuilder.WriteString(scanner.Text())\n\t}\n\tresponse := responseBuilder.String()\n\tassert.Contains(t, response, \"HTTP/1.0 200\", \"should get a 200\")\n\tassert.Contains(t, response, \"it worked\", \"resp body should match\")\n}"} {"repo":"gin","file":"gin_integration_test.go","line":331,"symbol":"responseBuilder","kind":"variable","lang":"go","code":"responseBuilder strings.Builder"} {"repo":"gin","file":"gin_integration_test.go","line":340,"symbol":"TestBadFileDescriptor","kind":"function","lang":"go","code":"func TestBadFileDescriptor(t *testing.T) {\n\trouter := New()\n\trequire.Error(t, router.RunFd(0))\n}"} {"repo":"gin","file":"gin_integration_test.go","line":345,"symbol":"TestListener","kind":"function","lang":"go","code":"func TestListener(t *testing.T) {\n\trouter := New()\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\trequire.NoError(t, err)\n\tlistener, err := net.ListenTCP(\"tcp\", addr)\n\trequire.NoError(t, err)\n\tgo func() {\n\t\trouter.GET(\"/example\", func(c *Context) { c.String(http.StatusOK, \"it worked\") })\n\t\tassert.NoError(t, router.RunListener(listener))\n\t}()\n\t// have to wait for the goroutine to start and run the server\n\t// otherwise the main thread will complete\n\ttime.Sleep(5 * time.Millisecond)\n\n\tc, err := net.Dial(\"tcp\", listener.Addr().String())\n\trequire.NoError(t, err)\n\n\tfmt.Fprintf(c, \"GET /example HTTP/1.0\\r\\n\\r\\n\")\n\tscanner := bufio.NewScanner(c)\n\tvar responseBuilder strings.Builder\n\tfor scanner.Scan() {\n\t\tresponseBuilder.WriteString(scanner.Text())\n\t}\n\tresponse := responseBuilder.String()\n\tassert.Contains(t, response, \"HTTP/1.0 200\", \"should get a 200\")\n\tassert.Contains(t, response, \"it worked\", \"resp body should match\")\n}"} {"repo":"gin","file":"gin_integration_test.go","line":364,"symbol":"responseBuilder","kind":"variable","lang":"go","code":"responseBuilder strings.Builder"} {"repo":"gin","file":"gin_integration_test.go","line":373,"symbol":"TestBadListener","kind":"function","lang":"go","code":"func TestBadListener(t *testing.T) {\n\trouter := New()\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:10086\")\n\trequire.NoError(t, err)\n\tlistener, err := net.ListenTCP(\"tcp\", addr)\n\trequire.NoError(t, err)\n\tlistener.Close()\n\trequire.Error(t, router.RunListener(listener))\n}"} {"repo":"gin","file":"gin_integration_test.go","line":383,"symbol":"TestWithHttptestWithAutoSelectedPort","kind":"function","lang":"go","code":"func TestWithHttptestWithAutoSelectedPort(t *testing.T) {\n\trouter := New()\n\trouter.GET(\"/example\", func(c *Context) { c.String(http.StatusOK, \"it worked\") })\n\n\tts := httptest.NewServer(router)\n\tdefer ts.Close()\n\n\ttestRequest(t, ts.URL+\"/example\")\n}"} {"repo":"gin","file":"gin_integration_test.go","line":393,"symbol":"TestConcurrentHandleContext","kind":"function","lang":"go","code":"func TestConcurrentHandleContext(t *testing.T) {\n\trouter := New()\n\trouter.GET(\"/\", func(c *Context) {\n\t\tc.Request.URL.Path = \"/example\"\n\t\trouter.HandleContext(c)\n\t})\n\trouter.GET(\"/example\", func(c *Context) { c.String(http.StatusOK, \"it worked\") })\n\n\tvar wg sync.WaitGroup\n\titerations := 200\n\twg.Add(iterations)\n\tfor range iterations {\n\t\tgo func() {\n\t\t\treq, err := http.NewRequest(http.MethodGet, \"/\", nil)\n\t\t\tassert.NoError(t, err)\n\n\t\t\tw := httptest.NewRecorder()\n\t\t\trouter.ServeHTTP(w, req)\n\n\t\t\tassert.Equal(t, \"it worked\", w.Body.String(), \"resp body should match\")\n\t\t\tassert.Equal(t, 200, w.Code, \"should get a 200\")\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n}"} {"repo":"gin","file":"gin_integration_test.go","line":401,"symbol":"wg","kind":"variable","lang":"go","code":"wg sync.WaitGroup"} {"repo":"gin","file":"gin_integration_test.go","line":435,"symbol":"TestTreeRunDynamicRouting","kind":"function","lang":"go","code":"func TestTreeRunDynamicRouting(t *testing.T) {\n\trouter := New()\n\trouter.GET(\"/aa/*xx\", func(c *Context) { c.String(http.StatusOK, \"/aa/*xx\") })\n\trouter.GET(\"/ab/*xx\", func(c *Context) { c.String(http.StatusOK, \"/ab/*xx\") })\n\trouter.GET(\"/\", func(c *Context) { c.String(http.StatusOK, \"home\") })\n\trouter.GET(\"/:cc\", func(c *Context) { c.String(http.StatusOK, \"/:cc\") })\n\trouter.GET(\"/c1/:dd/e\", func(c *Context) { c.String(http.StatusOK, \"/c1/:dd/e\") })\n\trouter.GET(\"/c1/:dd/e1\", func(c *Context) { c.String(http.StatusOK, \"/c1/:dd/e1\") })\n\trouter.GET(\"/c1/:dd/f1\", func(c *Context) { c.String(http.StatusOK, \"/c1/:dd/f1\") })\n\trouter.GET(\"/c1/:dd/f2\", func(c *Context) { c.String(http.StatusOK, \"/c1/:dd/f2\") })\n\trouter.GET(\"/:cc/cc\", func(c *Context) { c.String(http.StatusOK, \"/:cc/cc\") })\n\trouter.GET(\"/:cc/:dd/ee\", func(c *Context) { c.String(http.StatusOK, \"/:cc/:dd/ee\") })\n\trouter.GET(\"/:cc/:dd/f\", func(c *Context) { c.String(http.StatusOK, \"/:cc/:dd/f\") })\n\trouter.GET(\"/:cc/:dd/:ee/ff\", func(c *Context) { c.String(http.StatusOK, \"/:cc/:dd/:ee/ff\") })\n\trouter.GET(\"/:cc/:dd/:ee/:ff/gg\", func(c *Context) { c.String(http.StatusOK, \"/:cc/:dd/:ee/:ff/gg\") })\n\trouter.GET(\"/:cc/:dd/:ee/:ff/:gg/h"} {"repo":"gin","file":"gin_integration_test.go","line":581,"symbol":"isWindows","kind":"function","lang":"go","code":"func isWindows() bool {\n\treturn runtime.GOOS == \"windows\"\n}"} {"repo":"gin","file":"gin_integration_test.go","line":585,"symbol":"TestEscapedColon","kind":"function","lang":"go","code":"func TestEscapedColon(t *testing.T) {\n\trouter := New()\n\tf := func(u string) {\n\t\trouter.GET(u, func(c *Context) { c.String(http.StatusOK, u) })\n\t}\n\tf(\"/r/r\\\\:r\")\n\tf(\"/r/r:r\")\n\tf(\"/r/r/:r\")\n\tf(\"/r/r/\\\\:r\")\n\tf(\"/r/r/r\\\\:r\")\n\tassert.Panics(t, func() {\n\t\tf(\"\\\\foo:\")\n\t})\n\n\trouter.updateRouteTrees()\n\tts := httptest.NewServer(router)\n\tdefer ts.Close()\n\n\ttestRequest(t, ts.URL+\"/r/r123\", \"\", \"/r/r:r\")\n\ttestRequest(t, ts.URL+\"/r/r:r\", \"\", \"/r/r\\\\:r\")\n\ttestRequest(t, ts.URL+\"/r/r/r123\", \"\", \"/r/r/:r\")\n\ttestRequest(t, ts.URL+\"/r/r/:r\", \"\", \"/r/r/\\\\:r\")\n\ttestRequest(t, ts.URL+\"/r/r/r:r\", \"\", \"/r/r/r\\\\:r\")\n}"} {"repo":"gin","file":"gin_test.go","line":27,"symbol":"formatAsDate","kind":"function","lang":"go","code":"func formatAsDate(t time.Time) string {\n\tyear, month, day := t.Date()\n\treturn fmt.Sprintf(\"%d/%02d/%02d\", year, month, day)\n}"} {"repo":"gin","file":"gin_test.go","line":32,"symbol":"setupHTMLFiles","kind":"function","lang":"go","code":"func setupHTMLFiles(t *testing.T, mode string, tls bool, loadMethod func(*Engine)) *httptest.Server {\n\tSetMode(mode)\n\tdefer SetMode(TestMode)\n\n\tvar router *Engine\n\tcaptureOutput(t, func() {\n\t\trouter = New()\n\t\trouter.Delims(\"{[{\", \"}]}\")\n\t\trouter.SetFuncMap(template.FuncMap{\n\t\t\t\"formatAsDate\": formatAsDate,\n\t\t})\n\t\tloadMethod(router)\n\t\trouter.GET(\"/test\", func(c *Context) {\n\t\t\tc.HTML(http.StatusOK, \"hello.tmpl\", map[string]string{\"name\": \"world\"})\n\t\t})\n\t\trouter.GET(\"/raw\", func(c *Context) {\n\t\t\tc.HTML(http.StatusOK, \"raw.tmpl\", map[string]any{\n\t\t\t\t\"now\": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), //nolint:gofumpt\n\t\t\t})\n\t\t})\n\t})\n\n\tvar ts *httptest.Server\n\n\tif tls {\n\t\tts = httptest.NewTLSServer(router)\n\t} else {\n\t\tts = httptest.NewServer(router)\n\t}\n\n\treturn ts\n}"} {"repo":"gin","file":"gin_test.go","line":36,"symbol":"router","kind":"variable","lang":"go","code":"router *Engine"} {"repo":"gin","file":"gin_test.go","line":54,"symbol":"ts","kind":"variable","lang":"go","code":"ts *httptest.Server"} {"repo":"gin","file":"gin_test.go","line":65,"symbol":"TestLoadHTMLGlobDebugMode","kind":"function","lang":"go","code":"func TestLoadHTMLGlobDebugMode(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tDebugMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLGlob(\"./testdata/template/*\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":85,"symbol":"TestH2c","kind":"function","lang":"go","code":"func TestH2c(t *testing.T) {\n\tln, err := net.Listen(\"tcp\", localhostIP+\":0\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tr := Default()\n\tr.UseH2C = true\n\tr.GET(\"/\", func(c *Context) {\n\t\tc.String(200, \"

Hello world

\")\n\t})\n\tgo func() {\n\t\terr := http.Serve(ln, r.Handler())\n\t\tif err != nil {\n\t\t\tt.Log(err)\n\t\t}\n\t}()\n\tdefer ln.Close()\n\n\turl := \"http://\" + ln.Addr().String() + \"/\"\n\n\thttpClient := http.Client{\n\t\tTransport: &http2.Transport{\n\t\t\tAllowHTTP: true,\n\t\t\tDialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) {\n\t\t\t\treturn net.Dial(netw, addr)\n\t\t\t},\n\t\t},\n\t}\n\n\tres, err := httpClient.Get(url)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":123,"symbol":"TestLoadHTMLGlobTestMode","kind":"function","lang":"go","code":"func TestLoadHTMLGlobTestMode(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tTestMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLGlob(\"./testdata/template/*\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":143,"symbol":"TestLoadHTMLGlobReleaseMode","kind":"function","lang":"go","code":"func TestLoadHTMLGlobReleaseMode(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tReleaseMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLGlob(\"./testdata/template/*\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":163,"symbol":"TestLoadHTMLGlobUsingTLS","kind":"function","lang":"go","code":"func TestLoadHTMLGlobUsingTLS(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tDebugMode,\n\t\ttrue,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLGlob(\"./testdata/template/*\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\t// Use InsecureSkipVerify for avoiding `x509: certificate signed by unknown authority` error\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t}\n\tclient := &http.Client{Transport: tr}\n\tres, err := client.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":190,"symbol":"TestLoadHTMLGlobFromFuncMap","kind":"function","lang":"go","code":"func TestLoadHTMLGlobFromFuncMap(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tDebugMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLGlob(\"./testdata/template/*\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/raw\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"Date: 2017/07/01\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":210,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tSetMode(TestMode)\n}"} {"repo":"gin","file":"gin_test.go","line":214,"symbol":"TestCreateEngine","kind":"function","lang":"go","code":"func TestCreateEngine(t *testing.T) {\n\trouter := New()\n\tassert.Equal(t, \"/\", router.basePath)\n\tassert.Equal(t, router.engine, router)\n\tassert.Empty(t, router.Handlers)\n}"} {"repo":"gin","file":"gin_test.go","line":221,"symbol":"TestLoadHTMLFilesTestMode","kind":"function","lang":"go","code":"func TestLoadHTMLFilesTestMode(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tTestMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLFiles(\"./testdata/template/hello.tmpl\", \"./testdata/template/raw.tmpl\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":241,"symbol":"TestLoadHTMLFilesDebugMode","kind":"function","lang":"go","code":"func TestLoadHTMLFilesDebugMode(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tDebugMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLFiles(\"./testdata/template/hello.tmpl\", \"./testdata/template/raw.tmpl\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":261,"symbol":"TestLoadHTMLFilesReleaseMode","kind":"function","lang":"go","code":"func TestLoadHTMLFilesReleaseMode(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tReleaseMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLFiles(\"./testdata/template/hello.tmpl\", \"./testdata/template/raw.tmpl\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":281,"symbol":"TestLoadHTMLFilesUsingTLS","kind":"function","lang":"go","code":"func TestLoadHTMLFilesUsingTLS(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tTestMode,\n\t\ttrue,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLFiles(\"./testdata/template/hello.tmpl\", \"./testdata/template/raw.tmpl\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\t// Use InsecureSkipVerify for avoiding `x509: certificate signed by unknown authority` error\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t}\n\tclient := &http.Client{Transport: tr}\n\tres, err := client.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":308,"symbol":"TestLoadHTMLFilesFuncMap","kind":"function","lang":"go","code":"func TestLoadHTMLFilesFuncMap(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tTestMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLFiles(\"./testdata/template/hello.tmpl\", \"./testdata/template/raw.tmpl\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/raw\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"Date: 2017/07/01\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":328,"symbol":"tmplFS","kind":"variable","lang":"go","code":"tmplFS = http.Dir(\"testdata/template\")"} {"repo":"gin","file":"gin_test.go","line":330,"symbol":"TestLoadHTMLFSTestMode","kind":"function","lang":"go","code":"func TestLoadHTMLFSTestMode(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tTestMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLFS(tmplFS, \"hello.tmpl\", \"raw.tmpl\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":350,"symbol":"TestLoadHTMLFSDebugMode","kind":"function","lang":"go","code":"func TestLoadHTMLFSDebugMode(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tDebugMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLFS(tmplFS, \"hello.tmpl\", \"raw.tmpl\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":370,"symbol":"TestLoadHTMLFSReleaseMode","kind":"function","lang":"go","code":"func TestLoadHTMLFSReleaseMode(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tReleaseMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLFS(tmplFS, \"hello.tmpl\", \"raw.tmpl\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":390,"symbol":"TestLoadHTMLFSUsingTLS","kind":"function","lang":"go","code":"func TestLoadHTMLFSUsingTLS(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tTestMode,\n\t\ttrue,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLFS(tmplFS, \"hello.tmpl\", \"raw.tmpl\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\t// Use InsecureSkipVerify for avoiding `x509: certificate signed by unknown authority` error\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t}\n\tclient := &http.Client{Transport: tr}\n\tres, err := client.Get(ts.URL + \"/test\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"

Hello world

\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":417,"symbol":"TestLoadHTMLFSFuncMap","kind":"function","lang":"go","code":"func TestLoadHTMLFSFuncMap(t *testing.T) {\n\tts := setupHTMLFiles(\n\t\tt,\n\t\tTestMode,\n\t\tfalse,\n\t\tfunc(router *Engine) {\n\t\t\trouter.LoadHTMLFS(tmplFS, \"hello.tmpl\", \"raw.tmpl\")\n\t\t},\n\t)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"/raw\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tresp, _ := io.ReadAll(res.Body)\n\tassert.Equal(t, \"Date: 2017/07/01\", string(resp))\n}"} {"repo":"gin","file":"gin_test.go","line":437,"symbol":"TestAddRoute","kind":"function","lang":"go","code":"func TestAddRoute(t *testing.T) {\n\trouter := New()\n\trouter.addRoute(http.MethodGet, \"/\", HandlersChain{func(_ *Context) {}})\n\n\tassert.Len(t, router.trees, 1)\n\tassert.NotNil(t, router.trees.get(http.MethodGet))\n\tassert.Nil(t, router.trees.get(http.MethodPost))\n\n\trouter.addRoute(http.MethodPost, \"/\", HandlersChain{func(_ *Context) {}})\n\n\tassert.Len(t, router.trees, 2)\n\tassert.NotNil(t, router.trees.get(http.MethodGet))\n\tassert.NotNil(t, router.trees.get(http.MethodPost))\n\n\trouter.addRoute(http.MethodPost, \"/post\", HandlersChain{func(_ *Context) {}})\n\tassert.Len(t, router.trees, 2)\n}"} {"repo":"gin","file":"gin_test.go","line":455,"symbol":"TestAddRouteFails","kind":"function","lang":"go","code":"func TestAddRouteFails(t *testing.T) {\n\trouter := New()\n\tassert.Panics(t, func() { router.addRoute(\"\", \"/\", HandlersChain{func(_ *Context) {}}) })\n\tassert.Panics(t, func() { router.addRoute(http.MethodGet, \"a\", HandlersChain{func(_ *Context) {}}) })\n\tassert.Panics(t, func() { router.addRoute(http.MethodGet, \"/\", HandlersChain{}) })\n\n\trouter.addRoute(http.MethodPost, \"/post\", HandlersChain{func(_ *Context) {}})\n\tassert.Panics(t, func() {\n\t\trouter.addRoute(http.MethodPost, \"/post\", HandlersChain{func(_ *Context) {}})\n\t})\n}"} {"repo":"gin","file":"gin_test.go","line":467,"symbol":"TestCreateDefaultRouter","kind":"function","lang":"go","code":"func TestCreateDefaultRouter(t *testing.T) {\n\trouter := Default()\n\tassert.Len(t, router.Handlers, 2)\n}"} {"repo":"gin","file":"gin_test.go","line":472,"symbol":"TestNoRouteWithoutGlobalHandlers","kind":"function","lang":"go","code":"func TestNoRouteWithoutGlobalHandlers(t *testing.T) {\n\tvar middleware0 HandlerFunc = func(c *Context) {}\n\tvar middleware1 HandlerFunc = func(c *Context) {}\n\n\trouter := New()\n\n\trouter.NoRoute(middleware0)\n\tassert.Nil(t, router.Handlers)\n\tassert.Len(t, router.noRoute, 1)\n\tassert.Len(t, router.allNoRoute, 1)\n\tcompareFunc(t, router.noRoute[0], middleware0)\n\tcompareFunc(t, router.allNoRoute[0], middleware0)\n\n\trouter.NoRoute(middleware1, middleware0)\n\tassert.Len(t, router.noRoute, 2)\n\tassert.Len(t, router.allNoRoute, 2)\n\tcompareFunc(t, router.noRoute[0], middleware1)\n\tcompareFunc(t, router.allNoRoute[0], middleware1)\n\tcompareFunc(t, router.noRoute[1], middleware0)\n\tcompareFunc(t, router.allNoRoute[1], middleware0)\n}"} {"repo":"gin","file":"gin_test.go","line":473,"symbol":"middleware0","kind":"variable","lang":"go","code":"middleware0 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":474,"symbol":"middleware1","kind":"variable","lang":"go","code":"middleware1 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":494,"symbol":"TestNoRouteWithGlobalHandlers","kind":"function","lang":"go","code":"func TestNoRouteWithGlobalHandlers(t *testing.T) {\n\tvar middleware0 HandlerFunc = func(c *Context) {}\n\tvar middleware1 HandlerFunc = func(c *Context) {}\n\tvar middleware2 HandlerFunc = func(c *Context) {}\n\n\trouter := New()\n\trouter.Use(middleware2)\n\n\trouter.NoRoute(middleware0)\n\tassert.Len(t, router.allNoRoute, 2)\n\tassert.Len(t, router.Handlers, 1)\n\tassert.Len(t, router.noRoute, 1)\n\n\tcompareFunc(t, router.Handlers[0], middleware2)\n\tcompareFunc(t, router.noRoute[0], middleware0)\n\tcompareFunc(t, router.allNoRoute[0], middleware2)\n\tcompareFunc(t, router.allNoRoute[1], middleware0)\n\n\trouter.Use(middleware1)\n\tassert.Len(t, router.allNoRoute, 3)\n\tassert.Len(t, router.Handlers, 2)\n\tassert.Len(t, router.noRoute, 1)\n\n\tcompareFunc(t, router.Handlers[0], middleware2)\n\tcompareFunc(t, router.Handlers[1], middleware1)\n\tcompareFunc(t, router.noRoute[0], middleware0)\n\tcompareFunc(t, router.allNoRoute[0], middleware2)\n\tcompareFunc(t, router.allNoRoute[1], middleware1)\n\tcompareFunc(t, router.allNoRoute[2], middleware0)\n}"} {"repo":"gin","file":"gin_test.go","line":495,"symbol":"middleware0","kind":"variable","lang":"go","code":"middleware0 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":496,"symbol":"middleware1","kind":"variable","lang":"go","code":"middleware1 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":497,"symbol":"middleware2","kind":"variable","lang":"go","code":"middleware2 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":525,"symbol":"TestNoMethodWithoutGlobalHandlers","kind":"function","lang":"go","code":"func TestNoMethodWithoutGlobalHandlers(t *testing.T) {\n\tvar middleware0 HandlerFunc = func(c *Context) {}\n\tvar middleware1 HandlerFunc = func(c *Context) {}\n\n\trouter := New()\n\n\trouter.NoMethod(middleware0)\n\tassert.Empty(t, router.Handlers)\n\tassert.Len(t, router.noMethod, 1)\n\tassert.Len(t, router.allNoMethod, 1)\n\tcompareFunc(t, router.noMethod[0], middleware0)\n\tcompareFunc(t, router.allNoMethod[0], middleware0)\n\n\trouter.NoMethod(middleware1, middleware0)\n\tassert.Len(t, router.noMethod, 2)\n\tassert.Len(t, router.allNoMethod, 2)\n\tcompareFunc(t, router.noMethod[0], middleware1)\n\tcompareFunc(t, router.allNoMethod[0], middleware1)\n\tcompareFunc(t, router.noMethod[1], middleware0)\n\tcompareFunc(t, router.allNoMethod[1], middleware0)\n}"} {"repo":"gin","file":"gin_test.go","line":526,"symbol":"middleware0","kind":"variable","lang":"go","code":"middleware0 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":527,"symbol":"middleware1","kind":"variable","lang":"go","code":"middleware1 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":547,"symbol":"TestRebuild404Handlers","kind":"function","lang":"go","code":"func TestRebuild404Handlers(t *testing.T) {\n\tvar middleware0 HandlerFunc = func(c *Context) {}\n\tvar middleware1 HandlerFunc = func(c *Context) {}\n\n\trouter := New()\n\n\t// Initially, allNoRoute should be nil\n\tassert.Nil(t, router.allNoRoute)\n\n\t// Set NoRoute handlers\n\trouter.NoRoute(middleware0)\n\tassert.Len(t, router.allNoRoute, 1)\n\tassert.Len(t, router.noRoute, 1)\n\tcompareFunc(t, router.allNoRoute[0], middleware0)\n\n\t// Add Use middleware should trigger rebuild404Handlers\n\trouter.Use(middleware1)\n\tassert.Len(t, router.allNoRoute, 2)\n\tassert.Len(t, router.Handlers, 1)\n\tassert.Len(t, router.noRoute, 1)\n\n\t// Global middleware should come first\n\tcompareFunc(t, router.allNoRoute[0], middleware1)\n\tcompareFunc(t, router.allNoRoute[1], middleware0)\n}"} {"repo":"gin","file":"gin_test.go","line":548,"symbol":"middleware0","kind":"variable","lang":"go","code":"middleware0 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":549,"symbol":"middleware1","kind":"variable","lang":"go","code":"middleware1 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":573,"symbol":"TestNoMethodWithGlobalHandlers","kind":"function","lang":"go","code":"func TestNoMethodWithGlobalHandlers(t *testing.T) {\n\tvar middleware0 HandlerFunc = func(c *Context) {}\n\tvar middleware1 HandlerFunc = func(c *Context) {}\n\tvar middleware2 HandlerFunc = func(c *Context) {}\n\n\trouter := New()\n\trouter.Use(middleware2)\n\n\trouter.NoMethod(middleware0)\n\tassert.Len(t, router.allNoMethod, 2)\n\tassert.Len(t, router.Handlers, 1)\n\tassert.Len(t, router.noMethod, 1)\n\n\tcompareFunc(t, router.Handlers[0], middleware2)\n\tcompareFunc(t, router.noMethod[0], middleware0)\n\tcompareFunc(t, router.allNoMethod[0], middleware2)\n\tcompareFunc(t, router.allNoMethod[1], middleware0)\n\n\trouter.Use(middleware1)\n\tassert.Len(t, router.allNoMethod, 3)\n\tassert.Len(t, router.Handlers, 2)\n\tassert.Len(t, router.noMethod, 1)\n\n\tcompareFunc(t, router.Handlers[0], middleware2)\n\tcompareFunc(t, router.Handlers[1], middleware1)\n\tcompareFunc(t, router.noMethod[0], middleware0)\n\tcompareFunc(t, router.allNoMethod[0], middleware2)\n\tcompareFunc(t, router.allNoMethod[1], middleware1)\n\tcompareFunc(t, router.allNoMethod[2], middleware0)\n}"} {"repo":"gin","file":"gin_test.go","line":574,"symbol":"middleware0","kind":"variable","lang":"go","code":"middleware0 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":575,"symbol":"middleware1","kind":"variable","lang":"go","code":"middleware1 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":576,"symbol":"middleware2","kind":"variable","lang":"go","code":"middleware2 HandlerFunc = func(c *Context) {}"} {"repo":"gin","file":"gin_test.go","line":604,"symbol":"compareFunc","kind":"function","lang":"go","code":"func compareFunc(t *testing.T, a, b any) {\n\tsf1 := reflect.ValueOf(a)\n\tsf2 := reflect.ValueOf(b)\n\tif sf1.Pointer() != sf2.Pointer() {\n\t\tt.Error(\"different functions\")\n\t}\n}"} {"repo":"gin","file":"gin_test.go","line":612,"symbol":"TestListOfRoutes","kind":"function","lang":"go","code":"func TestListOfRoutes(t *testing.T) {\n\trouter := New()\n\trouter.GET(\"/favicon.ico\", handlerTest1)\n\trouter.GET(\"/\", handlerTest1)\n\tgroup := router.Group(\"/users\")\n\t{\n\t\tgroup.GET(\"/\", handlerTest2)\n\t\tgroup.GET(\"/:id\", handlerTest1)\n\t\tgroup.POST(\"/:id\", handlerTest2)\n\t}\n\trouter.Static(\"/static\", \".\")\n\n\tlist := router.Routes()\n\n\tassert.Len(t, list, 7)\n\tassertRoutePresent(t, list, RouteInfo{\n\t\tMethod: http.MethodGet,\n\t\tPath: \"/favicon.ico\",\n\t\tHandler: \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$\",\n\t})\n\tassertRoutePresent(t, list, RouteInfo{\n\t\tMethod: http.MethodGet,\n\t\tPath: \"/\",\n\t\tHandler: \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$\",\n\t})\n\tassertRoutePresent(t, list, RouteInfo{\n\t\tMethod: http.MethodGet,\n\t\tPath: \"/users/\",\n\t\tHandler: \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$\",\n\t})\n\tassertRoutePresent(t, list, RouteInfo{\n\t\tMethod: http.MethodGet,\n\t\tPath: \"/users/:id\",\n\t\tHandler: \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$\",\n\t})\n\tassertRoutePresent(t, list, RouteInfo{\n\t\tMethod: http.MethodPost,\n\t\tPath: \"/users/:id\",\n\t\tHandler: \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$\",\n\t})\n}"} {"repo":"gin","file":"gin_test.go","line":654,"symbol":"TestEngineHandleContext","kind":"function","lang":"go","code":"func TestEngineHandleContext(t *testing.T) {\n\tr := New()\n\tr.GET(\"/\", func(c *Context) {\n\t\tc.Request.URL.Path = \"/v2\"\n\t\tr.HandleContext(c)\n\t})\n\tv2 := r.Group(\"/v2\")\n\t{\n\t\tv2.GET(\"/\", func(c *Context) {})\n\t}\n\n\tassert.NotPanics(t, func() {\n\t\tw := PerformRequest(r, http.MethodGet, \"/\")\n\t\tassert.Equal(t, 301, w.Code)\n\t})\n}"} {"repo":"gin","file":"gin_test.go","line":671,"symbol":"TestEngineHandleContextManyReEntries","kind":"function","lang":"go","code":"func TestEngineHandleContextManyReEntries(t *testing.T) {\n\texpectValue := 10000\n\n\tvar handlerCounter, middlewareCounter int64\n\n\tr := New()\n\tr.Use(func(c *Context) {\n\t\tatomic.AddInt64(&middlewareCounter, 1)\n\t})\n\tr.GET(\"/:count\", func(c *Context) {\n\t\tcountStr := c.Param(\"count\")\n\t\tcount, err := strconv.Atoi(countStr)\n\t\trequire.NoError(t, err)\n\n\t\tn, err := c.Writer.Write([]byte(\".\"))\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, 1, n)\n\n\t\tswitch {\n\t\tcase count > 0:\n\t\t\tc.Request.URL.Path = \"/\" + strconv.Itoa(count-1)\n\t\t\tr.HandleContext(c)\n\t\t}\n\t}, func(c *Context) {\n\t\tatomic.AddInt64(&handlerCounter, 1)\n\t})\n\n\tassert.NotPanics(t, func() {\n\t\tw := PerformRequest(r, http.MethodGet, \"/\"+strconv.Itoa(expectValue-1)) // include 0 value\n\t\tassert.Equal(t, 200, w.Code)\n\t\tassert.Equal(t, expectValue, w.Body.Len())\n\t})\n\n\tassert.Equal(t, int64(expectValue), handlerCounter)\n\tassert.Equal(t, int64(expectValue), middlewareCounter)\n}"} {"repo":"gin","file":"gin_test.go","line":674,"symbol":"handlerCounter","kind":"variable","lang":"go","code":"handlerCounter, middlewareCounter int64"} {"repo":"gin","file":"gin_test.go","line":674,"symbol":"middlewareCounter","kind":"variable","lang":"go","code":"handlerCounter, middlewareCounter int64"} {"repo":"gin","file":"gin_test.go","line":708,"symbol":"TestEngineHandleContextPreventsMiddlewareReEntry","kind":"function","lang":"go","code":"func TestEngineHandleContextPreventsMiddlewareReEntry(t *testing.T) {\n\t// given\n\tvar handlerCounterV1, handlerCounterV2, middlewareCounterV1 int64\n\n\tr := New()\n\tv1 := r.Group(\"/v1\")\n\t{\n\t\tv1.Use(func(c *Context) {\n\t\t\tatomic.AddInt64(&middlewareCounterV1, 1)\n\t\t})\n\t\tv1.GET(\"/test\", func(c *Context) {\n\t\t\tatomic.AddInt64(&handlerCounterV1, 1)\n\t\t\tc.Status(http.StatusOK)\n\t\t})\n\t}\n\n\tv2 := r.Group(\"/v2\")\n\t{\n\t\tv2.GET(\"/test\", func(c *Context) {\n\t\t\tc.Request.URL.Path = \"/v1/test\"\n\t\t\tr.HandleContext(c)\n\t\t}, func(c *Context) {\n\t\t\tatomic.AddInt64(&handlerCounterV2, 1)\n\t\t})\n\t}\n\n\t// when\n\tresponseV1 := PerformRequest(r, \"GET\", \"/v1/test\")\n\tresponseV2 := PerformRequest(r, \"GET\", \"/v2/test\")\n\n\t// then\n\tassert.Equal(t, 200, responseV1.Code)\n\tassert.Equal(t, 200, responseV2.Code)\n\tassert.Equal(t, int64(2), handlerCounterV1)\n\tassert.Equal(t, int64(2), middlewareCounterV1)\n\tassert.Equal(t, int64(1), handlerCounterV2)\n}"} {"repo":"gin","file":"gin_test.go","line":710,"symbol":"handlerCounterV1","kind":"variable","lang":"go","doc":"given","code":"handlerCounterV1, handlerCounterV2, middlewareCounterV1 int64"} {"repo":"gin","file":"gin_test.go","line":710,"symbol":"handlerCounterV2","kind":"variable","lang":"go","doc":"given","code":"handlerCounterV1, handlerCounterV2, middlewareCounterV1 int64"} {"repo":"gin","file":"gin_test.go","line":710,"symbol":"middlewareCounterV1","kind":"variable","lang":"go","doc":"given","code":"handlerCounterV1, handlerCounterV2, middlewareCounterV1 int64"} {"repo":"gin","file":"gin_test.go","line":746,"symbol":"TestEngineHandleContextNoRouteWithGroupMiddleware","kind":"function","lang":"go","code":"func TestEngineHandleContextNoRouteWithGroupMiddleware(t *testing.T) {\n\t// Scenario from issue #1848:\n\t// - Engine with no global middleware (gin.New())\n\t// - A group with middleware\n\t// - A route in that group\n\t// - NoRoute handler that redirects via HandleContext\n\t// The group middleware should run exactly once per HandleContext call,\n\t// not accumulate across redirects.\n\n\tvar middlewareCount, handlerCount int64\n\n\tr := New()\n\tgrp := r.Group(\"\", func(c *Context) {\n\t\tatomic.AddInt64(&middlewareCount, 1)\n\t\tc.Next()\n\t})\n\tgrp.GET(\"/target\", func(c *Context) {\n\t\tatomic.AddInt64(&handlerCount, 1)\n\t\tc.String(http.StatusOK, \"ok\")\n\t})\n\n\tr.NoRoute(func(c *Context) {\n\t\tc.Request.URL.Path = \"/target\"\n\t\tr.HandleContext(c)\n\t})\n\n\t// Access a non-existent route to trigger NoRoute -> HandleContext\n\tw := PerformRequest(r, \"GET\", \"/nonexistent\")\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"ok\", w.Body.String())\n\t// Middleware and handler should each run exactly once\n\tassert.Equal(t, int64(1), atomic.LoadInt64(&middlewareCount))\n\tassert.Equal(t, int64(1), atomic.LoadInt64(&handlerCount))\n}"} {"repo":"gin","file":"gin_test.go","line":755,"symbol":"middlewareCount","kind":"variable","lang":"go","code":"middlewareCount, handlerCount int64"} {"repo":"gin","file":"gin_test.go","line":755,"symbol":"handlerCount","kind":"variable","lang":"go","code":"middlewareCount, handlerCount int64"} {"repo":"gin","file":"gin_test.go","line":781,"symbol":"TestEngineHandleContextNoRouteWithEngineMiddleware","kind":"function","lang":"go","code":"func TestEngineHandleContextNoRouteWithEngineMiddleware(t *testing.T) {\n\t// When engine middleware exists and NoRoute redirects via HandleContext,\n\t// verify the handlers run the expected number of times.\n\n\tvar engineMwCount, groupMwCount, handlerCount int64\n\n\tr := New()\n\tr.Use(func(c *Context) {\n\t\tatomic.AddInt64(&engineMwCount, 1)\n\t\tc.Next()\n\t})\n\n\tgrp := r.Group(\"\", func(c *Context) {\n\t\tatomic.AddInt64(&groupMwCount, 1)\n\t\tc.Next()\n\t})\n\tgrp.GET(\"/target\", func(c *Context) {\n\t\tatomic.AddInt64(&handlerCount, 1)\n\t\tc.String(http.StatusOK, \"ok\")\n\t})\n\n\tr.NoRoute(func(c *Context) {\n\t\tc.Request.URL.Path = \"/target\"\n\t\tr.HandleContext(c)\n\t})\n\n\tw := PerformRequest(r, \"GET\", \"/nonexistent\")\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"ok\", w.Body.String())\n\t// Handler and group middleware should each run once (from HandleContext)\n\tassert.Equal(t, int64(1), atomic.LoadInt64(&handlerCount))\n\tassert.Equal(t, int64(1), atomic.LoadInt64(&groupMwCount))\n\t// Engine middleware runs twice: once for the NoRoute chain, once for the HandleContext chain\n\t// This is expected behavior since HandleContext re-enters the full handler chain\n\tassert.Equal(t, int64(2), atomic.LoadInt64(&engineMwCount"} {"repo":"gin","file":"gin_test.go","line":785,"symbol":"engineMwCount","kind":"variable","lang":"go","code":"engineMwCount, groupMwCount, handlerCount int64"} {"repo":"gin","file":"gin_test.go","line":785,"symbol":"groupMwCount","kind":"variable","lang":"go","code":"engineMwCount, groupMwCount, handlerCount int64"} {"repo":"gin","file":"gin_test.go","line":785,"symbol":"handlerCount","kind":"variable","lang":"go","code":"engineMwCount, groupMwCount, handlerCount int64"} {"repo":"gin","file":"githubapi_test.go","line":21,"symbol":"route","kind":"type","lang":"go","code":"type route struct {\n\tmethod string\n\tpath string\n}"} {"repo":"gin","file":"githubapi_test.go","line":27,"symbol":"githubAPI","kind":"variable","lang":"go","doc":"http://developer.github.com/v3/","code":"githubAPI = []route{\n\t// OAuth Authorizations\n\t{http.MethodGet, \"/authorizations\"},\n\t{http.MethodGet, \"/authorizations/:id\"},\n\t{http.MethodPost, \"/authorizations\"},\n\t//{http.MethodPut, \"/authorizations/clients/:client_id\"},\n\t//{http.MethodPatch, \"/authorizations/:id\"},\n\t{http.MethodDelete, \"/authorizations/:id\"},\n\t{http.MethodGet, \"/applications/:client_id/tokens/:access_token\"},\n\t{http.MethodDelete, \"/applications/:client_id/tokens\"},\n\t{http.MethodDelete, \"/applications/:client_id/tokens/:access_token\"},\n\n\t// Activity\n\t{http.MethodGet, \"/events\"},\n\t{http.MethodGet, \"/repos/:owner/:repo/events\"},\n\t{http.MethodGet, \"/networks/:owner/:repo/events\"},\n\t{http.MethodGet, \"/orgs/:org/events\"},\n\t{http.MethodGet, \"/users/:user/received_events\"},\n\t{http.MethodGet, \"/users/:user/received_events/public\"},\n\t{http.MethodGet, \"/users/:user/events\"},\n\t{http.MethodGet, \"/users/:user/events/public\"},\n\t{http.MethodGet, \"/users/:user/events/orgs/:org\"},\n\t{http.MethodGet, \"/feeds\"},\n\t{http.MethodGet, \"/notifications\"},\n\t{http.MethodGet, \"/repos/:owner/:repo/notifications\"},\n\t{http.MethodPut, \"/notifications\"},\n\t{http.MethodPut, \"/repos/:owner/:repo/notifications\"},\n\t{http.MethodGet, \"/notifications/thr"} {"repo":"gin","file":"githubapi_test.go","line":290,"symbol":"TestShouldBindUri","kind":"function","lang":"go","code":"func TestShouldBindUri(t *testing.T) {\n\tDefaultWriter = os.Stdout\n\trouter := New()\n\n\ttype Person struct {\n\t\tName string `uri:\"name\" binding:\"required\"`\n\t\tID string `uri:\"id\" binding:\"required\"`\n\t}\n\trouter.Handle(http.MethodGet, \"/rest/:name/:id\", func(c *Context) {\n\t\tvar person Person\n\t\trequire.NoError(t, c.ShouldBindUri(&person))\n\t\tassert.NotEmpty(t, person.Name)\n\t\tassert.NotEmpty(t, person.ID)\n\t\tc.String(http.StatusOK, \"ShouldBindUri test OK\")\n\t})\n\n\tpath, _ := exampleFromPath(\"/rest/:name/:id\")\n\tw := PerformRequest(router, http.MethodGet, path)\n\tassert.Equal(t, \"ShouldBindUri test OK\", w.Body.String())\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"repo":"gin","file":"githubapi_test.go","line":294,"symbol":"Person","kind":"type","lang":"go","code":"type Person struct {\n\t\tName string `uri:\"name\" binding:\"required\"`\n\t\tID string `uri:\"id\" binding:\"required\"`\n\t}"} {"repo":"gin","file":"githubapi_test.go","line":299,"symbol":"person","kind":"variable","lang":"go","code":"person Person"} {"repo":"gin","file":"githubapi_test.go","line":312,"symbol":"TestBindUri","kind":"function","lang":"go","code":"func TestBindUri(t *testing.T) {\n\tDefaultWriter = os.Stdout\n\trouter := New()\n\n\ttype Person struct {\n\t\tName string `uri:\"name\" binding:\"required\"`\n\t\tID string `uri:\"id\" binding:\"required\"`\n\t}\n\trouter.Handle(http.MethodGet, \"/rest/:name/:id\", func(c *Context) {\n\t\tvar person Person\n\t\trequire.NoError(t, c.BindUri(&person))\n\t\tassert.NotEmpty(t, person.Name)\n\t\tassert.NotEmpty(t, person.ID)\n\t\tc.String(http.StatusOK, \"BindUri test OK\")\n\t})\n\n\tpath, _ := exampleFromPath(\"/rest/:name/:id\")\n\tw := PerformRequest(router, http.MethodGet, path)\n\tassert.Equal(t, \"BindUri test OK\", w.Body.String())\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"repo":"gin","file":"githubapi_test.go","line":316,"symbol":"Person","kind":"type","lang":"go","code":"type Person struct {\n\t\tName string `uri:\"name\" binding:\"required\"`\n\t\tID string `uri:\"id\" binding:\"required\"`\n\t}"} {"repo":"gin","file":"githubapi_test.go","line":321,"symbol":"person","kind":"variable","lang":"go","code":"person Person"} {"repo":"gin","file":"githubapi_test.go","line":334,"symbol":"TestBindUriError","kind":"function","lang":"go","code":"func TestBindUriError(t *testing.T) {\n\tDefaultWriter = os.Stdout\n\trouter := New()\n\n\ttype Member struct {\n\t\tNumber string `uri:\"num\" binding:\"required,uuid\"`\n\t}\n\trouter.Handle(http.MethodGet, \"/new/rest/:num\", func(c *Context) {\n\t\tvar m Member\n\t\trequire.Error(t, c.BindUri(&m))\n\t})\n\n\tpath1, _ := exampleFromPath(\"/new/rest/:num\")\n\tw1 := PerformRequest(router, http.MethodGet, path1)\n\tassert.Equal(t, http.StatusBadRequest, w1.Code)\n}"} {"repo":"gin","file":"githubapi_test.go","line":338,"symbol":"Member","kind":"type","lang":"go","code":"type Member struct {\n\t\tNumber string `uri:\"num\" binding:\"required,uuid\"`\n\t}"} {"repo":"gin","file":"githubapi_test.go","line":342,"symbol":"m","kind":"variable","lang":"go","code":"m Member"} {"repo":"gin","file":"githubapi_test.go","line":351,"symbol":"TestRaceContextCopy","kind":"function","lang":"go","code":"func TestRaceContextCopy(t *testing.T) {\n\tDefaultWriter = os.Stdout\n\trouter := Default()\n\trouter.GET(\"/test/copy/race\", func(c *Context) {\n\t\tc.Set(\"1\", 0)\n\t\tc.Set(\"2\", 0)\n\n\t\t// Sending a copy of the Context to two separate routines\n\t\tgo readWriteKeys(c.Copy())\n\t\tgo readWriteKeys(c.Copy())\n\t\tc.String(http.StatusOK, \"run OK, no panics\")\n\t})\n\tw := PerformRequest(router, http.MethodGet, \"/test/copy/race\")\n\tassert.Equal(t, \"run OK, no panics\", w.Body.String())\n}"} {"repo":"gin","file":"githubapi_test.go","line":367,"symbol":"readWriteKeys","kind":"function","lang":"go","code":"func readWriteKeys(c *Context) {\n\tfor {\n\t\tc.Set(\"1\", rand.Int())\n\t\tc.Set(\"2\", c.Value(\"1\"))\n\t}\n}"} {"repo":"gin","file":"githubapi_test.go","line":374,"symbol":"githubConfigRouter","kind":"function","lang":"go","code":"func githubConfigRouter(router *Engine) {\n\tfor _, route := range githubAPI {\n\t\trouter.Handle(route.method, route.path, func(c *Context) {\n\t\t\toutput := make(map[string]string, len(c.Params)+1)\n\t\t\toutput[\"status\"] = \"good\"\n\t\t\tfor _, param := range c.Params {\n\t\t\t\toutput[param.Key] = param.Value\n\t\t\t}\n\t\t\tc.JSON(http.StatusOK, output)\n\t\t})\n\t}\n}"} {"repo":"gin","file":"githubapi_test.go","line":387,"symbol":"TestGithubAPI","kind":"function","lang":"go","code":"func TestGithubAPI(t *testing.T) {\n\tDefaultWriter = os.Stdout\n\trouter := New()\n\tgithubConfigRouter(router)\n\n\tfor _, route := range githubAPI {\n\t\tpath, values := exampleFromPath(route.path)\n\t\tw := PerformRequest(router, route.method, path)\n\n\t\t// TEST\n\t\tassert.Contains(t, w.Body.String(), \"\\\"status\\\":\\\"good\\\"\")\n\t\tfor _, value := range values {\n\t\t\tstr := fmt.Sprintf(\"\\\"%s\\\":\\\"%s\\\"\", value.Key, value.Value)\n\t\t\tassert.Contains(t, w.Body.String(), str)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"githubapi_test.go","line":405,"symbol":"exampleFromPath","kind":"function","lang":"go","code":"func exampleFromPath(path string) (string, Params) {\n\toutput := new(strings.Builder)\n\tparams := make(Params, 0, 6)\n\tstart := -1\n\tfor i, c := range path {\n\t\tif c == ':' {\n\t\t\tstart = i + 1\n\t\t}\n\t\tif start >= 0 {\n\t\t\tif c == '/' {\n\t\t\t\tvalue := strconv.Itoa(rand.Intn(100000))\n\t\t\t\tparams = append(params, Param{\n\t\t\t\t\tKey: path[start:i],\n\t\t\t\t\tValue: value,\n\t\t\t\t})\n\t\t\t\toutput.WriteString(value)\n\t\t\t\toutput.WriteRune(c)\n\t\t\t\tstart = -1\n\t\t\t}\n\t\t} else {\n\t\t\toutput.WriteRune(c)\n\t\t}\n\t}\n\tif start >= 0 {\n\t\tvalue := strconv.Itoa(rand.Intn(100000))\n\t\tparams = append(params, Param{\n\t\t\tKey: path[start:],\n\t\t\tValue: value,\n\t\t})\n\t\toutput.WriteString(value)\n\t}\n\n\treturn output.String(), params\n}"} {"repo":"gin","file":"githubapi_test.go","line":440,"symbol":"BenchmarkGithub","kind":"function","lang":"go","code":"func BenchmarkGithub(b *testing.B) {\n\trouter := New()\n\tgithubConfigRouter(router)\n\trunRequest(b, router, http.MethodGet, \"/legacy/issues/search/:owner/:repository/:state/:keyword\")\n}"} {"repo":"gin","file":"githubapi_test.go","line":446,"symbol":"BenchmarkParallelGithub","kind":"function","lang":"go","code":"func BenchmarkParallelGithub(b *testing.B) {\n\tDefaultWriter = os.Stdout\n\trouter := New()\n\tgithubConfigRouter(router)\n\n\treq, _ := http.NewRequest(http.MethodPost, \"/repos/manucorporat/sse/git/blobs\", nil)\n\n\tb.RunParallel(func(pb *testing.PB) {\n\t\t// Each goroutine has its own bytes.Buffer.\n\t\tfor pb.Next() {\n\t\t\tw := httptest.NewRecorder()\n\t\t\trouter.ServeHTTP(w, req)\n\t\t}\n\t})\n}"} {"repo":"gin","file":"githubapi_test.go","line":462,"symbol":"BenchmarkParallelGithubDefault","kind":"function","lang":"go","code":"func BenchmarkParallelGithubDefault(b *testing.B) {\n\tDefaultWriter = os.Stdout\n\trouter := New()\n\tgithubConfigRouter(router)\n\n\treq, _ := http.NewRequest(http.MethodPost, \"/repos/manucorporat/sse/git/blobs\", nil)\n\n\tb.RunParallel(func(pb *testing.PB) {\n\t\t// Each goroutine has its own bytes.Buffer.\n\t\tfor pb.Next() {\n\t\t\tw := httptest.NewRecorder()\n\t\t\trouter.ServeHTTP(w, req)\n\t\t}\n\t})\n}"} {"repo":"gin","file":"go.mod","line":1,"symbol":"github.com/gin-gonic/gin","kind":"module","lang":"gomod","code":"module github.com/gin-gonic/gin"} {"repo":"gin","file":"internal/bytesconv/bytesconv.go","line":13,"symbol":"StringToBytes","kind":"function","lang":"go","doc":"StringToBytes converts string to byte slice without a memory allocation. For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077.","code":"func StringToBytes(s string) []byte {\n\treturn unsafe.Slice(unsafe.StringData(s), len(s))\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv.go","line":19,"symbol":"BytesToString","kind":"function","lang":"go","doc":"BytesToString converts byte slice to string without a memory allocation. For more details, see https://github.com/golang/go/issues/53003#issuecomment-1140276077.","code":"func BytesToString(b []byte) string {\n\treturn unsafe.String(unsafe.SliceData(b), len(b))\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":17,"symbol":"testString","kind":"variable","lang":"go","code":"testString = \"Albert Einstein: Logic will get you from A to B. Imagination will take you everywhere.\""} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":18,"symbol":"testBytes","kind":"variable","lang":"go","code":"testBytes = []byte(testString)"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":21,"symbol":"rawBytesToStr","kind":"function","lang":"go","code":"func rawBytesToStr(b []byte) string {\n\treturn string(b)\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":25,"symbol":"rawStrToBytes","kind":"function","lang":"go","code":"func rawStrToBytes(s string) []byte {\n\treturn []byte(s)\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":31,"symbol":"TestBytesToString","kind":"function","lang":"go","code":"func TestBytesToString(t *testing.T) {\n\tdata := make([]byte, 1024)\n\tfor range 100 {\n\t\t_, err := cRand.Read(data)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif rawBytesToStr(data) != BytesToString(data) {\n\t\t\tt.Fatal(\"don't match\")\n\t\t}\n\t}\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":44,"symbol":"TestBytesToStringEmpty","kind":"function","lang":"go","code":"func TestBytesToStringEmpty(t *testing.T) {\n\tif got := BytesToString([]byte{}); got != \"\" {\n\t\tt.Fatalf(\"BytesToString([]byte{}) = %q; want empty string\", got)\n\t}\n\tif got := BytesToString(nil); got != \"\" {\n\t\tt.Fatalf(\"BytesToString(nil) = %q; want empty string\", got)\n\t}\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":53,"symbol":"letterBytes","kind":"constant","lang":"go","code":"letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\""} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":55,"symbol":"letterIdxBits","kind":"constant","lang":"go","code":"letterIdxBits = 6"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":56,"symbol":"letterIdxMask","kind":"constant","lang":"go","code":"letterIdxMask = 1<= 0; {\n\t\tif remain == 0 {\n\t\t\tcache, remain = src.Int63(), letterIdxMax\n\t\t}\n\t\tif idx := int(cache & letterIdxMask); idx < len(letterBytes) {\n\t\t\tsb.WriteByte(letterBytes[idx])\n\t\t\ti--\n\t\t}\n\t\tcache >>= letterIdxBits\n\t\tremain--\n\t}\n\n\treturn sb.String()\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":81,"symbol":"TestStringToBytes","kind":"function","lang":"go","code":"func TestStringToBytes(t *testing.T) {\n\tfor range 100 {\n\t\ts := RandStringBytesMaskImprSrcSB(64)\n\t\tif !bytes.Equal(rawStrToBytes(s), StringToBytes(s)) {\n\t\t\tt.Fatal(\"don't match\")\n\t\t}\n\t}\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":90,"symbol":"TestStringToBytesEmpty","kind":"function","lang":"go","code":"func TestStringToBytesEmpty(t *testing.T) {\n\tb := StringToBytes(\"\")\n\tif len(b) != 0 {\n\t\tt.Fatalf(`StringToBytes(\"\") length = %d; want 0`, len(b))\n\t}\n\tif !bytes.Equal(b, []byte(\"\")) {\n\t\tt.Fatalf(`StringToBytes(\"\") = %v; want []byte(\"\")`, b)\n\t}\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":102,"symbol":"BenchmarkBytesConvBytesToStrRaw","kind":"function","lang":"go","code":"func BenchmarkBytesConvBytesToStrRaw(b *testing.B) {\n\tfor b.Loop() {\n\t\trawBytesToStr(testBytes)\n\t}\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":108,"symbol":"BenchmarkBytesConvBytesToStr","kind":"function","lang":"go","code":"func BenchmarkBytesConvBytesToStr(b *testing.B) {\n\tfor b.Loop() {\n\t\tBytesToString(testBytes)\n\t}\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":114,"symbol":"BenchmarkBytesConvStrToBytesRaw","kind":"function","lang":"go","code":"func BenchmarkBytesConvStrToBytesRaw(b *testing.B) {\n\tfor b.Loop() {\n\t\trawStrToBytes(testString)\n\t}\n}"} {"repo":"gin","file":"internal/bytesconv/bytesconv_test.go","line":120,"symbol":"BenchmarkBytesConvStrToBytes","kind":"function","lang":"go","code":"func BenchmarkBytesConvStrToBytes(b *testing.B) {\n\tfor b.Loop() {\n\t\tStringToBytes(testString)\n\t}\n}"} {"repo":"gin","file":"internal/fs/fs.go","line":9,"symbol":"FileSystem","kind":"type","lang":"go","doc":"FileSystem implements an [fs.FS].","code":"type FileSystem struct {\n\thttp.FileSystem\n}"} {"repo":"gin","file":"internal/fs/fs.go","line":14,"symbol":"Open","kind":"method","lang":"go","doc":"Open passes `Open` to the upstream implementation and return an [fs.File].","code":"func (o FileSystem) Open(name string) (fs.File, error) {\n\tf, err := o.FileSystem.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn fs.File(f), nil\n}"} {"repo":"gin","file":"internal/fs/fs_test.go","line":13,"symbol":"mockFileSystem","kind":"type","lang":"go","code":"type mockFileSystem struct {\n\topen func(name string) (http.File, error)\n}"} {"repo":"gin","file":"internal/fs/fs_test.go","line":17,"symbol":"Open","kind":"method","lang":"go","code":"func (m *mockFileSystem) Open(name string) (http.File, error) {\n\treturn m.open(name)\n}"} {"repo":"gin","file":"internal/fs/fs_test.go","line":21,"symbol":"TestFileSystem_Open","kind":"function","lang":"go","code":"func TestFileSystem_Open(t *testing.T) {\n\tvar testFile *os.File\n\tmockFS := &mockFileSystem{\n\t\topen: func(name string) (http.File, error) {\n\t\t\treturn testFile, nil\n\t\t},\n\t}\n\tfs := &FileSystem{mockFS}\n\n\tfile, err := fs.Open(\"foo\")\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, testFile, file)\n}"} {"repo":"gin","file":"internal/fs/fs_test.go","line":22,"symbol":"testFile","kind":"variable","lang":"go","code":"testFile *os.File"} {"repo":"gin","file":"internal/fs/fs_test.go","line":36,"symbol":"TestFileSystem_Open_err","kind":"function","lang":"go","code":"func TestFileSystem_Open_err(t *testing.T) {\n\ttestError := errors.New(\"mock\")\n\tmockFS := &mockFileSystem{\n\t\topen: func(_ string) (http.File, error) {\n\t\t\treturn nil, testError\n\t\t},\n\t}\n\tfs := &FileSystem{mockFS}\n\n\tfile, err := fs.Open(\"foo\")\n\n\trequire.ErrorIs(t, err, testError)\n\tassert.Nil(t, file)\n}"} {"repo":"gin","file":"logger.go","line":17,"symbol":"consoleColorModeValue","kind":"type","lang":"go","code":"type consoleColorModeValue int"} {"repo":"gin","file":"logger.go","line":20,"symbol":"autoColor","kind":"constant","lang":"go","code":"autoColor consoleColorModeValue = iota"} {"repo":"gin","file":"logger.go","line":21,"symbol":"disableColor","kind":"constant","lang":"go","code":"disableColor"} {"repo":"gin","file":"logger.go","line":22,"symbol":"forceColor","kind":"constant","lang":"go","code":"forceColor"} {"repo":"gin","file":"logger.go","line":26,"symbol":"green","kind":"constant","lang":"go","code":"green = \"\\033[97;42m\""} {"repo":"gin","file":"logger.go","line":27,"symbol":"white","kind":"constant","lang":"go","code":"white = \"\\033[90;47m\""} {"repo":"gin","file":"logger.go","line":28,"symbol":"yellow","kind":"constant","lang":"go","code":"yellow = \"\\033[90;43m\""} {"repo":"gin","file":"logger.go","line":29,"symbol":"red","kind":"constant","lang":"go","code":"red = \"\\033[97;41m\""} {"repo":"gin","file":"logger.go","line":30,"symbol":"blue","kind":"constant","lang":"go","code":"blue = \"\\033[97;44m\""} {"repo":"gin","file":"logger.go","line":31,"symbol":"magenta","kind":"constant","lang":"go","code":"magenta = \"\\033[97;45m\""} {"repo":"gin","file":"logger.go","line":32,"symbol":"cyan","kind":"constant","lang":"go","code":"cyan = \"\\033[97;46m\""} {"repo":"gin","file":"logger.go","line":33,"symbol":"reset","kind":"constant","lang":"go","code":"reset = \"\\033[0m\""} {"repo":"gin","file":"logger.go","line":36,"symbol":"consoleColorMode","kind":"variable","lang":"go","code":"consoleColorMode = autoColor"} {"repo":"gin","file":"logger.go","line":39,"symbol":"LoggerConfig","kind":"type","lang":"go","doc":"LoggerConfig defines the config for Logger middleware.","code":"type LoggerConfig struct {\n\t// Optional. Default value is gin.defaultLogFormatter\n\tFormatter LogFormatter\n\n\t// Output is a writer where logs are written.\n\t// Optional. Default value is gin.DefaultWriter.\n\tOutput io.Writer\n\n\t// SkipPaths is a URL path array which logs are not written.\n\t// Optional.\n\tSkipPaths []string\n\n\t// SkipQueryString indicates that query strings should not be written\n\t// for cases such as when API keys are passed via query strings.\n\t// Optional. Default value is false.\n\tSkipQueryString bool\n\n\t// Skip is a Skipper that indicates which logs should not be written.\n\t// Optional.\n\tSkip Skipper\n}"} {"repo":"gin","file":"logger.go","line":62,"symbol":"Skipper","kind":"type","lang":"go","doc":"Skipper is a function to skip logs based on provided Context","code":"type Skipper func(c *Context) bool"} {"repo":"gin","file":"logger.go","line":65,"symbol":"LogFormatter","kind":"type","lang":"go","doc":"LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter","code":"type LogFormatter func(params LogFormatterParams) string"} {"repo":"gin","file":"logger.go","line":68,"symbol":"LogFormatterParams","kind":"type","lang":"go","doc":"LogFormatterParams is the structure any formatter will be handed when time to log comes","code":"type LogFormatterParams struct {\n\tRequest *http.Request\n\n\t// TimeStamp shows the time after the server returns a response.\n\tTimeStamp time.Time\n\t// StatusCode is HTTP response code.\n\tStatusCode int\n\t// Latency is how much time the server cost to process a certain request.\n\tLatency time.Duration\n\t// ClientIP equals Context's ClientIP method.\n\tClientIP string\n\t// Method is the HTTP method given to the request.\n\tMethod string\n\t// Path is a path the client requests.\n\tPath string\n\t// ErrorMessage is set if error has occurred in processing the request.\n\tErrorMessage string\n\t// isTerm shows whether gin's output descriptor refers to a terminal.\n\tisTerm bool\n\t// BodySize is the size of the Response Body\n\tBodySize int\n\t// Keys are the keys set on the request's context.\n\tKeys map[any]any\n}"} {"repo":"gin","file":"logger.go","line":94,"symbol":"StatusCodeColor","kind":"method","lang":"go","doc":"StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.","code":"func (p *LogFormatterParams) StatusCodeColor() string {\n\tcode := p.StatusCode\n\n\tswitch {\n\tcase code >= http.StatusContinue && code < http.StatusOK:\n\t\treturn white\n\tcase code >= http.StatusOK && code < http.StatusMultipleChoices:\n\t\treturn green\n\tcase code >= http.StatusMultipleChoices && code < http.StatusBadRequest:\n\t\treturn white\n\tcase code >= http.StatusBadRequest && code < http.StatusInternalServerError:\n\t\treturn yellow\n\tdefault:\n\t\treturn red\n\t}\n}"} {"repo":"gin","file":"logger.go","line":112,"symbol":"LatencyColor","kind":"method","lang":"go","doc":"LatencyColor is the ANSI color for latency","code":"func (p *LogFormatterParams) LatencyColor() string {\n\tlatency := p.Latency\n\tswitch {\n\tcase latency < time.Millisecond*100:\n\t\treturn white\n\tcase latency < time.Millisecond*200:\n\t\treturn green\n\tcase latency < time.Millisecond*300:\n\t\treturn cyan\n\tcase latency < time.Millisecond*500:\n\t\treturn blue\n\tcase latency < time.Second:\n\t\treturn yellow\n\tcase latency < time.Second*2:\n\t\treturn magenta\n\tdefault:\n\t\treturn red\n\t}\n}"} {"repo":"gin","file":"logger.go","line":133,"symbol":"MethodColor","kind":"method","lang":"go","doc":"MethodColor is the ANSI color for appropriately logging http method to a terminal.","code":"func (p *LogFormatterParams) MethodColor() string {\n\tmethod := p.Method\n\n\tswitch method {\n\tcase http.MethodGet:\n\t\treturn blue\n\tcase http.MethodPost:\n\t\treturn cyan\n\tcase http.MethodPut:\n\t\treturn yellow\n\tcase http.MethodDelete:\n\t\treturn red\n\tcase http.MethodPatch:\n\t\treturn green\n\tcase http.MethodHead:\n\t\treturn magenta\n\tcase http.MethodOptions:\n\t\treturn white\n\tdefault:\n\t\treturn reset\n\t}\n}"} {"repo":"gin","file":"logger.go","line":157,"symbol":"ResetColor","kind":"method","lang":"go","doc":"ResetColor resets all escape attributes.","code":"func (p *LogFormatterParams) ResetColor() string {\n\treturn reset\n}"} {"repo":"gin","file":"logger.go","line":162,"symbol":"IsOutputColor","kind":"method","lang":"go","doc":"IsOutputColor indicates whether can colors be outputted to the log.","code":"func (p *LogFormatterParams) IsOutputColor() bool {\n\treturn consoleColorMode == forceColor || (consoleColorMode == autoColor && p.isTerm)\n}"} {"repo":"gin","file":"logger.go","line":167,"symbol":"defaultLogFormatter","kind":"variable","lang":"go","doc":"defaultLogFormatter is the default log format function Logger middleware uses.","code":"defaultLogFormatter = func(param LogFormatterParams) string {\n\tvar statusColor, methodColor, resetColor, latencyColor string\n\tif param.IsOutputColor() {\n\t\tstatusColor = param.StatusCodeColor()\n\t\tmethodColor = param.MethodColor()\n\t\tresetColor = param.ResetColor()\n\t\tlatencyColor = param.LatencyColor()\n\t}\n\n\tswitch {\n\tcase param.Latency > time.Minute:\n\t\tparam.Latency = param.Latency.Truncate(time.Second * 10)\n\tcase param.Latency > time.Second:\n\t\tparam.Latency = param.Latency.Truncate(time.Millisecond * 10)\n\tcase param.Latency > time.Millisecond:\n\t\tparam.Latency = param.Latency.Truncate(time.Microsecond * 10)\n\t}\n\n\treturn fmt.Sprintf(\"[GIN] %v |%s %3d %s|%s %8v %s| %15s |%s %-7s %s %#v\\n%s\",\n\t\tparam.TimeStamp.Format(\"2006/01/02 - 15:04:05\"),\n\t\tstatusColor, param.StatusCode, resetColor,\n\t\tlatencyColor, param.Latency, resetColor,\n\t\tparam.ClientIP,\n\t\tmethodColor, param.Method, resetColor,\n\t\tparam.Path,\n\t\tparam.ErrorMessage,\n\t)\n}"} {"repo":"gin","file":"logger.go","line":168,"symbol":"statusColor","kind":"variable","lang":"go","code":"statusColor, methodColor, resetColor, latencyColor string"} {"repo":"gin","file":"logger.go","line":168,"symbol":"methodColor","kind":"variable","lang":"go","code":"statusColor, methodColor, resetColor, latencyColor string"} {"repo":"gin","file":"logger.go","line":168,"symbol":"resetColor","kind":"variable","lang":"go","code":"statusColor, methodColor, resetColor, latencyColor string"} {"repo":"gin","file":"logger.go","line":168,"symbol":"latencyColor","kind":"variable","lang":"go","code":"statusColor, methodColor, resetColor, latencyColor string"} {"repo":"gin","file":"logger.go","line":197,"symbol":"DisableConsoleColor","kind":"function","lang":"go","doc":"DisableConsoleColor disables color output in the console.","code":"func DisableConsoleColor() {\n\tconsoleColorMode = disableColor\n}"} {"repo":"gin","file":"logger.go","line":202,"symbol":"ForceConsoleColor","kind":"function","lang":"go","doc":"ForceConsoleColor force color output in the console.","code":"func ForceConsoleColor() {\n\tconsoleColorMode = forceColor\n}"} {"repo":"gin","file":"logger.go","line":207,"symbol":"ErrorLogger","kind":"function","lang":"go","doc":"ErrorLogger returns a HandlerFunc for any error type.","code":"func ErrorLogger() HandlerFunc {\n\treturn ErrorLoggerT(ErrorTypeAny)\n}"} {"repo":"gin","file":"logger.go","line":212,"symbol":"ErrorLoggerT","kind":"function","lang":"go","doc":"ErrorLoggerT returns a HandlerFunc for a given error type.","code":"func ErrorLoggerT(typ ErrorType) HandlerFunc {\n\treturn func(c *Context) {\n\t\tc.Next()\n\t\terrors := c.Errors.ByType(typ)\n\t\tif len(errors) > 0 {\n\t\t\tc.JSON(-1, errors)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"logger.go","line":224,"symbol":"Logger","kind":"function","lang":"go","doc":"Logger instances a Logger middleware that will write the logs to gin.DefaultWriter. By default, gin.DefaultWriter = os.Stdout.","code":"func Logger() HandlerFunc {\n\treturn LoggerWithConfig(LoggerConfig{})\n}"} {"repo":"gin","file":"logger.go","line":229,"symbol":"LoggerWithFormatter","kind":"function","lang":"go","doc":"LoggerWithFormatter instance a Logger middleware with the specified log format function.","code":"func LoggerWithFormatter(f LogFormatter) HandlerFunc {\n\treturn LoggerWithConfig(LoggerConfig{\n\t\tFormatter: f,\n\t})\n}"} {"repo":"gin","file":"logger.go","line":237,"symbol":"LoggerWithWriter","kind":"function","lang":"go","doc":"LoggerWithWriter instance a Logger middleware with the specified writer buffer. Example: os.Stdout, a file opened in write mode, a socket...","code":"func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {\n\treturn LoggerWithConfig(LoggerConfig{\n\t\tOutput: out,\n\t\tSkipPaths: notlogged,\n\t})\n}"} {"repo":"gin","file":"logger.go","line":245,"symbol":"LoggerWithConfig","kind":"function","lang":"go","doc":"LoggerWithConfig instance a Logger middleware with config.","code":"func LoggerWithConfig(conf LoggerConfig) HandlerFunc {\n\tformatter := conf.Formatter\n\tif formatter == nil {\n\t\tformatter = defaultLogFormatter\n\t}\n\n\tout := conf.Output\n\tif out == nil {\n\t\tout = DefaultWriter\n\t}\n\n\tnotlogged := conf.SkipPaths\n\n\tisTerm := true\n\n\tif w, ok := out.(*os.File); !ok || os.Getenv(\"TERM\") == \"dumb\" ||\n\t\t(!isatty.IsTerminal(w.Fd()) && !isatty.IsCygwinTerminal(w.Fd())) {\n\t\tisTerm = false\n\t}\n\n\tvar skip map[string]struct{}\n\n\tif length := len(notlogged); length > 0 {\n\t\tskip = make(map[string]struct{}, length)\n\n\t\tfor _, path := range notlogged {\n\t\t\tskip[path] = struct{}{}\n\t\t}\n\t}\n\n\treturn func(c *Context) {\n\t\t// Start timer\n\t\tstart := time.Now()\n\t\tpath := c.Request.URL.Path\n\t\traw := c.Request.URL.RawQuery\n\n\t\t// Process request\n\t\tc.Next()\n\n\t\t// Log only when it is not being skipped\n\t\tif _, ok := skip[path]; ok || (conf.Skip != nil && conf.Skip(c)) {\n\t\t\treturn\n\t\t}\n\n\t\tparam := LogFormatterParams{\n\t\t\tRequest: c.Request,\n\t\t\tisTerm: isTerm,\n\t\t\tKeys: c.Keys,\n\t\t}\n\n\t\t// Stop timer\n\t\tparam.TimeStamp = time.Now()\n\t\tparam.Latency = param.TimeStamp.Sub(start)\n\n\t\tparam.ClientIP = c.ClientIP()\n\t\tparam.Method = c.Request.Method\n\t\tparam.StatusCode = c.Writer.Status()\n\t\tparam.ErrorMe"} {"repo":"gin","file":"logger.go","line":265,"symbol":"skip","kind":"variable","lang":"go","code":"skip map[string]struct{}"} {"repo":"gin","file":"logger_test.go","line":18,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tSetMode(TestMode)\n}"} {"repo":"gin","file":"logger_test.go","line":22,"symbol":"TestLogger","kind":"function","lang":"go","code":"func TestLogger(t *testing.T) {\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\trouter.Use(LoggerWithWriter(buffer))\n\trouter.GET(\"/example\", func(c *Context) {})\n\trouter.POST(\"/example\", func(c *Context) {})\n\trouter.PUT(\"/example\", func(c *Context) {})\n\trouter.DELETE(\"/example\", func(c *Context) {})\n\trouter.PATCH(\"/example\", func(c *Context) {})\n\trouter.HEAD(\"/example\", func(c *Context) {})\n\trouter.OPTIONS(\"/example\", func(c *Context) {})\n\n\tPerformRequest(router, http.MethodGet, \"/example?a=100\")\n\tassert.Contains(t, buffer.String(), \"200\")\n\tassert.Contains(t, buffer.String(), http.MethodGet)\n\tassert.Contains(t, buffer.String(), \"/example\")\n\tassert.Contains(t, buffer.String(), \"a=100\")\n\n\t// I wrote these first (extending the above) but then realized they are more\n\t// like integration tests because they test the whole logging process rather\n\t// than individual functions. I'm not sure where these should go.\n\tbuffer.Reset()\n\tPerformRequest(router, http.MethodPost, \"/example\")\n\tassert.Contains(t, buffer.String(), \"200\")\n\tassert.Contains(t, buffer.String(), http.MethodPost)\n\tassert.Contains(t, buffer.String(), \"/example\")\n\n\tbuffer.Reset()\n\tPerformRequest(router, http.MethodPut, \"/examp"} {"repo":"gin","file":"logger_test.go","line":86,"symbol":"TestLoggerWithConfig","kind":"function","lang":"go","code":"func TestLoggerWithConfig(t *testing.T) {\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\trouter.Use(LoggerWithConfig(LoggerConfig{Output: buffer}))\n\trouter.GET(\"/example\", func(c *Context) {})\n\trouter.POST(\"/example\", func(c *Context) {})\n\trouter.PUT(\"/example\", func(c *Context) {})\n\trouter.DELETE(\"/example\", func(c *Context) {})\n\trouter.PATCH(\"/example\", func(c *Context) {})\n\trouter.HEAD(\"/example\", func(c *Context) {})\n\trouter.OPTIONS(\"/example\", func(c *Context) {})\n\n\tPerformRequest(router, http.MethodGet, \"/example?a=100\")\n\tassert.Contains(t, buffer.String(), \"200\")\n\tassert.Contains(t, buffer.String(), http.MethodGet)\n\tassert.Contains(t, buffer.String(), \"/example\")\n\tassert.Contains(t, buffer.String(), \"a=100\")\n\n\t// I wrote these first (extending the above) but then realized they are more\n\t// like integration tests because they test the whole logging process rather\n\t// than individual functions. I'm not sure where these should go.\n\tbuffer.Reset()\n\tPerformRequest(router, http.MethodPost, \"/example\")\n\tassert.Contains(t, buffer.String(), \"200\")\n\tassert.Contains(t, buffer.String(), http.MethodPost)\n\tassert.Contains(t, buffer.String(), \"/example\")\n\n\tbuffer.Reset()\n\tPerformRequest"} {"repo":"gin","file":"logger_test.go","line":150,"symbol":"TestLoggerWithFormatter","kind":"function","lang":"go","code":"func TestLoggerWithFormatter(t *testing.T) {\n\tbuffer := new(strings.Builder)\n\n\td := DefaultWriter\n\tDefaultWriter = buffer\n\tdefer func() {\n\t\tDefaultWriter = d\n\t}()\n\n\trouter := New()\n\trouter.Use(LoggerWithFormatter(func(param LogFormatterParams) string {\n\t\treturn fmt.Sprintf(\"[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %#v\\n%s\",\n\t\t\tparam.TimeStamp.Format(\"2006/01/02 - 15:04:05\"),\n\t\t\tparam.StatusCode,\n\t\t\tparam.Latency,\n\t\t\tparam.ClientIP,\n\t\t\tparam.Method,\n\t\t\tparam.Path,\n\t\t\tparam.ErrorMessage,\n\t\t)\n\t}))\n\trouter.GET(\"/example\", func(c *Context) {})\n\tPerformRequest(router, http.MethodGet, \"/example?a=100\")\n\n\t// output test\n\tassert.Contains(t, buffer.String(), \"[FORMATTER TEST]\")\n\tassert.Contains(t, buffer.String(), \"200\")\n\tassert.Contains(t, buffer.String(), http.MethodGet)\n\tassert.Contains(t, buffer.String(), \"/example\")\n\tassert.Contains(t, buffer.String(), \"a=100\")\n}"} {"repo":"gin","file":"logger_test.go","line":182,"symbol":"TestLoggerWithConfigFormatting","kind":"function","lang":"go","code":"func TestLoggerWithConfigFormatting(t *testing.T) {\n\tvar gotParam LogFormatterParams\n\tvar gotKeys map[any]any\n\tbuffer := new(strings.Builder)\n\n\trouter := New()\n\trouter.engine.trustedCIDRs, _ = router.engine.prepareTrustedCIDRs()\n\n\trouter.Use(LoggerWithConfig(LoggerConfig{\n\t\tOutput: buffer,\n\t\tFormatter: func(param LogFormatterParams) string {\n\t\t\t// for assert test\n\t\t\tgotParam = param\n\n\t\t\treturn fmt.Sprintf(\"[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\\n%s\",\n\t\t\t\tparam.TimeStamp.Format(\"2006/01/02 - 15:04:05\"),\n\t\t\t\tparam.StatusCode,\n\t\t\t\tparam.Latency,\n\t\t\t\tparam.ClientIP,\n\t\t\t\tparam.Method,\n\t\t\t\tparam.Path,\n\t\t\t\tparam.ErrorMessage,\n\t\t\t)\n\t\t},\n\t}))\n\trouter.GET(\"/example\", func(c *Context) {\n\t\t// set dummy ClientIP\n\t\tc.Request.Header.Set(\"X-Forwarded-For\", \"20.20.20.20\")\n\t\tgotKeys = c.Keys\n\t\ttime.Sleep(time.Millisecond)\n\t})\n\tPerformRequest(router, http.MethodGet, \"/example?a=100\")\n\n\t// output test\n\tassert.Contains(t, buffer.String(), \"[FORMATTER TEST]\")\n\tassert.Contains(t, buffer.String(), \"200\")\n\tassert.Contains(t, buffer.String(), http.MethodGet)\n\tassert.Contains(t, buffer.String(), \"/example\")\n\tassert.Contains(t, buffer.String(), \"a=100\")\n\n\t// LogFormatterParams test\n\tassert.NotNil(t"} {"repo":"gin","file":"logger_test.go","line":183,"symbol":"gotParam","kind":"variable","lang":"go","code":"gotParam LogFormatterParams"} {"repo":"gin","file":"logger_test.go","line":184,"symbol":"gotKeys","kind":"variable","lang":"go","code":"gotKeys map[any]any"} {"repo":"gin","file":"logger_test.go","line":234,"symbol":"TestDefaultLogFormatter","kind":"function","lang":"go","code":"func TestDefaultLogFormatter(t *testing.T) {\n\ttimeStamp := time.Unix(1544173902, 0).UTC()\n\n\ttermFalseParam := LogFormatterParams{\n\t\tTimeStamp: timeStamp,\n\t\tStatusCode: 200,\n\t\tLatency: time.Second * 5,\n\t\tClientIP: \"20.20.20.20\",\n\t\tMethod: http.MethodGet,\n\t\tPath: \"/\",\n\t\tErrorMessage: \"\",\n\t\tisTerm: false,\n\t}\n\n\ttermTrueParam := LogFormatterParams{\n\t\tTimeStamp: timeStamp,\n\t\tStatusCode: 200,\n\t\tLatency: time.Second * 5,\n\t\tClientIP: \"20.20.20.20\",\n\t\tMethod: http.MethodGet,\n\t\tPath: \"/\",\n\t\tErrorMessage: \"\",\n\t\tisTerm: true,\n\t}\n\ttermTrueLongDurationParam := LogFormatterParams{\n\t\tTimeStamp: timeStamp,\n\t\tStatusCode: 200,\n\t\tLatency: time.Millisecond * 9876543210,\n\t\tClientIP: \"20.20.20.20\",\n\t\tMethod: http.MethodGet,\n\t\tPath: \"/\",\n\t\tErrorMessage: \"\",\n\t\tisTerm: true,\n\t}\n\n\ttermFalseLongDurationParam := LogFormatterParams{\n\t\tTimeStamp: timeStamp,\n\t\tStatusCode: 200,\n\t\tLatency: time.Millisecond * 9876543210,\n\t\tClientIP: \"20.20.20.20\",\n\t\tMethod: http.MethodGet,\n\t\tPath: \"/\",\n\t\tErrorMessage: \"\",\n\t\tisTerm: false,\n\t}\n\n\tassert.Equal(t, \"[GIN] 2018/12/07 - 09:11:42 | 200 | "} {"repo":"gin","file":"logger_test.go","line":287,"symbol":"TestColorForMethod","kind":"function","lang":"go","code":"func TestColorForMethod(t *testing.T) {\n\tcolorForMethod := func(method string) string {\n\t\tp := LogFormatterParams{\n\t\t\tMethod: method,\n\t\t}\n\t\treturn p.MethodColor()\n\t}\n\n\tassert.Equal(t, blue, colorForMethod(http.MethodGet), \"get should be blue\")\n\tassert.Equal(t, cyan, colorForMethod(http.MethodPost), \"post should be cyan\")\n\tassert.Equal(t, yellow, colorForMethod(http.MethodPut), \"put should be yellow\")\n\tassert.Equal(t, red, colorForMethod(http.MethodDelete), \"delete should be red\")\n\tassert.Equal(t, green, colorForMethod(\"PATCH\"), \"patch should be green\")\n\tassert.Equal(t, magenta, colorForMethod(\"HEAD\"), \"head should be magenta\")\n\tassert.Equal(t, white, colorForMethod(\"OPTIONS\"), \"options should be white\")\n\tassert.Equal(t, reset, colorForMethod(\"TRACE\"), \"trace is not defined and should be the reset color\")\n}"} {"repo":"gin","file":"logger_test.go","line":305,"symbol":"TestColorForStatus","kind":"function","lang":"go","code":"func TestColorForStatus(t *testing.T) {\n\tcolorForStatus := func(code int) string {\n\t\tp := LogFormatterParams{\n\t\t\tStatusCode: code,\n\t\t}\n\t\treturn p.StatusCodeColor()\n\t}\n\n\tassert.Equal(t, white, colorForStatus(http.StatusContinue), \"1xx should be white\")\n\tassert.Equal(t, green, colorForStatus(http.StatusOK), \"2xx should be green\")\n\tassert.Equal(t, white, colorForStatus(http.StatusMovedPermanently), \"3xx should be white\")\n\tassert.Equal(t, yellow, colorForStatus(http.StatusNotFound), \"4xx should be yellow\")\n\tassert.Equal(t, red, colorForStatus(2), \"other things should be red\")\n}"} {"repo":"gin","file":"logger_test.go","line":320,"symbol":"TestColorForLatency","kind":"function","lang":"go","code":"func TestColorForLatency(t *testing.T) {\n\tcolorForLatency := func(latency time.Duration) string {\n\t\tp := LogFormatterParams{\n\t\t\tLatency: latency,\n\t\t}\n\t\treturn p.LatencyColor()\n\t}\n\n\tassert.Equal(t, white, colorForLatency(time.Duration(0)), \"0 should be white\")\n\tassert.Equal(t, white, colorForLatency(time.Millisecond*20), \"20ms should be white\")\n\tassert.Equal(t, green, colorForLatency(time.Millisecond*150), \"150ms should be green\")\n\tassert.Equal(t, cyan, colorForLatency(time.Millisecond*250), \"250ms should be cyan\")\n\tassert.Equal(t, blue, colorForLatency(time.Millisecond*400), \"400ms should be blue\")\n\tassert.Equal(t, yellow, colorForLatency(time.Millisecond*600), \"600ms should be yellow\")\n\tassert.Equal(t, magenta, colorForLatency(time.Millisecond*1500), \"1.5s should be magenta\")\n\tassert.Equal(t, red, colorForLatency(time.Second*3), \"other things should be red\")\n}"} {"repo":"gin","file":"logger_test.go","line":338,"symbol":"TestResetColor","kind":"function","lang":"go","code":"func TestResetColor(t *testing.T) {\n\tp := LogFormatterParams{}\n\tassert.Equal(t, string([]byte{27, 91, 48, 109}), p.ResetColor())\n}"} {"repo":"gin","file":"logger_test.go","line":343,"symbol":"TestIsOutputColor","kind":"function","lang":"go","code":"func TestIsOutputColor(t *testing.T) {\n\t// test with isTerm flag true.\n\tp := LogFormatterParams{\n\t\tisTerm: true,\n\t}\n\n\tconsoleColorMode = autoColor\n\tassert.True(t, p.IsOutputColor())\n\n\tForceConsoleColor()\n\tassert.True(t, p.IsOutputColor())\n\n\tDisableConsoleColor()\n\tassert.False(t, p.IsOutputColor())\n\n\t// test with isTerm flag false.\n\tp = LogFormatterParams{\n\t\tisTerm: false,\n\t}\n\n\tconsoleColorMode = autoColor\n\tassert.False(t, p.IsOutputColor())\n\n\tForceConsoleColor()\n\tassert.True(t, p.IsOutputColor())\n\n\tDisableConsoleColor()\n\tassert.False(t, p.IsOutputColor())\n\n\t// reset console color mode.\n\tconsoleColorMode = autoColor\n}"} {"repo":"gin","file":"logger_test.go","line":376,"symbol":"TestErrorLogger","kind":"function","lang":"go","code":"func TestErrorLogger(t *testing.T) {\n\trouter := New()\n\trouter.Use(ErrorLogger())\n\trouter.GET(\"/error\", func(c *Context) {\n\t\tc.Error(errors.New(\"this is an error\")) //nolint: errcheck\n\t})\n\trouter.GET(\"/abort\", func(c *Context) {\n\t\tc.AbortWithError(http.StatusUnauthorized, errors.New(\"no authorized\")) //nolint: errcheck\n\t})\n\trouter.GET(\"/print\", func(c *Context) {\n\t\tc.Error(errors.New(\"this is an error\")) //nolint: errcheck\n\t\tc.String(http.StatusInternalServerError, \"hola!\")\n\t})\n\n\tw := PerformRequest(router, http.MethodGet, \"/error\")\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.JSONEq(t, \"{\\\"error\\\":\\\"this is an error\\\"}\", w.Body.String())\n\n\tw = PerformRequest(router, http.MethodGet, \"/abort\")\n\tassert.Equal(t, http.StatusUnauthorized, w.Code)\n\tassert.JSONEq(t, \"{\\\"error\\\":\\\"no authorized\\\"}\", w.Body.String())\n\n\tw = PerformRequest(router, http.MethodGet, \"/print\")\n\tassert.Equal(t, http.StatusInternalServerError, w.Code)\n\tassert.Equal(t, \"hola!{\\\"error\\\":\\\"this is an error\\\"}\", w.Body.String())\n}"} {"repo":"gin","file":"logger_test.go","line":403,"symbol":"TestLoggerWithWriterSkippingPaths","kind":"function","lang":"go","code":"func TestLoggerWithWriterSkippingPaths(t *testing.T) {\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\trouter.Use(LoggerWithWriter(buffer, \"/skipped\"))\n\trouter.GET(\"/logged\", func(c *Context) {})\n\trouter.GET(\"/skipped\", func(c *Context) {})\n\n\tPerformRequest(router, http.MethodGet, \"/logged\")\n\tassert.Contains(t, buffer.String(), \"200\")\n\n\tbuffer.Reset()\n\tPerformRequest(router, http.MethodGet, \"/skipped\")\n\tassert.Contains(t, buffer.String(), \"\")\n}"} {"repo":"gin","file":"logger_test.go","line":418,"symbol":"TestLoggerWithConfigSkippingPaths","kind":"function","lang":"go","code":"func TestLoggerWithConfigSkippingPaths(t *testing.T) {\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\trouter.Use(LoggerWithConfig(LoggerConfig{\n\t\tOutput: buffer,\n\t\tSkipPaths: []string{\"/skipped\"},\n\t}))\n\trouter.GET(\"/logged\", func(c *Context) {})\n\trouter.GET(\"/skipped\", func(c *Context) {})\n\n\tPerformRequest(router, http.MethodGet, \"/logged\")\n\tassert.Contains(t, buffer.String(), \"200\")\n\n\tbuffer.Reset()\n\tPerformRequest(router, http.MethodGet, \"/skipped\")\n\tassert.Contains(t, buffer.String(), \"\")\n}"} {"repo":"gin","file":"logger_test.go","line":436,"symbol":"TestLoggerWithConfigSkipper","kind":"function","lang":"go","code":"func TestLoggerWithConfigSkipper(t *testing.T) {\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\trouter.Use(LoggerWithConfig(LoggerConfig{\n\t\tOutput: buffer,\n\t\tSkip: func(c *Context) bool {\n\t\t\treturn c.Writer.Status() == http.StatusNoContent\n\t\t},\n\t}))\n\trouter.GET(\"/logged\", func(c *Context) { c.Status(http.StatusOK) })\n\trouter.GET(\"/skipped\", func(c *Context) { c.Status(http.StatusNoContent) })\n\n\tPerformRequest(router, http.MethodGet, \"/logged\")\n\tassert.Contains(t, buffer.String(), \"200\")\n\n\tbuffer.Reset()\n\tPerformRequest(router, http.MethodGet, \"/skipped\")\n\tassert.Contains(t, buffer.String(), \"\")\n}"} {"repo":"gin","file":"logger_test.go","line":456,"symbol":"TestDisableConsoleColor","kind":"function","lang":"go","code":"func TestDisableConsoleColor(t *testing.T) {\n\tNew()\n\tassert.Equal(t, autoColor, consoleColorMode)\n\tDisableConsoleColor()\n\tassert.Equal(t, disableColor, consoleColorMode)\n\n\t// reset console color mode.\n\tconsoleColorMode = autoColor\n}"} {"repo":"gin","file":"logger_test.go","line":466,"symbol":"TestForceConsoleColor","kind":"function","lang":"go","code":"func TestForceConsoleColor(t *testing.T) {\n\tNew()\n\tassert.Equal(t, autoColor, consoleColorMode)\n\tForceConsoleColor()\n\tassert.Equal(t, forceColor, consoleColorMode)\n\n\t// reset console color mode.\n\tconsoleColorMode = autoColor\n}"} {"repo":"gin","file":"logger_test.go","line":476,"symbol":"TestLoggerWithConfigSkipQueryString","kind":"function","lang":"go","code":"func TestLoggerWithConfigSkipQueryString(t *testing.T) {\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\trouter.Use(LoggerWithConfig(LoggerConfig{\n\t\tOutput: buffer,\n\t\tSkipQueryString: true,\n\t}))\n\trouter.GET(\"/logged\", func(c *Context) { c.Status(http.StatusOK) })\n\n\tPerformRequest(router, \"GET\", \"/logged?a=21\")\n\tassert.Contains(t, buffer.String(), \"200\")\n\tassert.NotContains(t, buffer.String(), \"a=21\")\n}"} {"repo":"gin","file":"middleware_test.go","line":17,"symbol":"TestMiddlewareGeneralCase","kind":"function","lang":"go","code":"func TestMiddlewareGeneralCase(t *testing.T) {\n\tsignature := \"\"\n\trouter := New()\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"A\"\n\t\tc.Next()\n\t\tsignature += \"B\"\n\t})\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"C\"\n\t})\n\trouter.GET(\"/\", func(c *Context) {\n\t\tsignature += \"D\"\n\t})\n\trouter.NoRoute(func(c *Context) {\n\t\tsignature += \" X \"\n\t})\n\trouter.NoMethod(func(c *Context) {\n\t\tsignature += \" XX \"\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/\")\n\n\t// TEST\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"ACDB\", signature)\n}"} {"repo":"gin","file":"middleware_test.go","line":45,"symbol":"TestMiddlewareNoRoute","kind":"function","lang":"go","code":"func TestMiddlewareNoRoute(t *testing.T) {\n\tsignature := \"\"\n\trouter := New()\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"A\"\n\t\tc.Next()\n\t\tsignature += \"B\"\n\t})\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"C\"\n\t\tc.Next()\n\t\tc.Next()\n\t\tc.Next()\n\t\tc.Next()\n\t\tsignature += \"D\"\n\t})\n\trouter.NoRoute(func(c *Context) {\n\t\tsignature += \"E\"\n\t\tc.Next()\n\t\tsignature += \"F\"\n\t}, func(c *Context) {\n\t\tsignature += \"G\"\n\t\tc.Next()\n\t\tsignature += \"H\"\n\t})\n\trouter.NoMethod(func(c *Context) {\n\t\tsignature += \" X \"\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/\")\n\n\t// TEST\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n\tassert.Equal(t, \"ACEGHFDB\", signature)\n}"} {"repo":"gin","file":"middleware_test.go","line":81,"symbol":"TestMiddlewareNoMethodEnabled","kind":"function","lang":"go","code":"func TestMiddlewareNoMethodEnabled(t *testing.T) {\n\tsignature := \"\"\n\trouter := New()\n\trouter.HandleMethodNotAllowed = true\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"A\"\n\t\tc.Next()\n\t\tsignature += \"B\"\n\t})\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"C\"\n\t\tc.Next()\n\t\tsignature += \"D\"\n\t})\n\trouter.NoMethod(func(c *Context) {\n\t\tsignature += \"E\"\n\t\tc.Next()\n\t\tsignature += \"F\"\n\t}, func(c *Context) {\n\t\tsignature += \"G\"\n\t\tc.Next()\n\t\tsignature += \"H\"\n\t})\n\trouter.NoRoute(func(c *Context) {\n\t\tsignature += \" X \"\n\t})\n\trouter.POST(\"/\", func(c *Context) {\n\t\tsignature += \" XX \"\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/\")\n\n\t// TEST\n\tassert.Equal(t, http.StatusMethodNotAllowed, w.Code)\n\tassert.Equal(t, \"ACEGHFDB\", signature)\n}"} {"repo":"gin","file":"middleware_test.go","line":118,"symbol":"TestMiddlewareNoMethodDisabled","kind":"function","lang":"go","code":"func TestMiddlewareNoMethodDisabled(t *testing.T) {\n\tsignature := \"\"\n\trouter := New()\n\n\t// NoMethod disabled\n\trouter.HandleMethodNotAllowed = false\n\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"A\"\n\t\tc.Next()\n\t\tsignature += \"B\"\n\t})\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"C\"\n\t\tc.Next()\n\t\tsignature += \"D\"\n\t})\n\trouter.NoMethod(func(c *Context) {\n\t\tsignature += \"E\"\n\t\tc.Next()\n\t\tsignature += \"F\"\n\t}, func(c *Context) {\n\t\tsignature += \"G\"\n\t\tc.Next()\n\t\tsignature += \"H\"\n\t})\n\trouter.NoRoute(func(c *Context) {\n\t\tsignature += \" X \"\n\t})\n\trouter.POST(\"/\", func(c *Context) {\n\t\tsignature += \" XX \"\n\t})\n\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/\")\n\n\t// TEST\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n\tassert.Equal(t, \"AC X DB\", signature)\n}"} {"repo":"gin","file":"middleware_test.go","line":159,"symbol":"TestMiddlewareAbort","kind":"function","lang":"go","code":"func TestMiddlewareAbort(t *testing.T) {\n\tsignature := \"\"\n\trouter := New()\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"A\"\n\t})\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"C\"\n\t\tc.AbortWithStatus(http.StatusUnauthorized)\n\t\tc.Next()\n\t\tsignature += \"D\"\n\t})\n\trouter.GET(\"/\", func(c *Context) {\n\t\tsignature += \" X \"\n\t\tc.Next()\n\t\tsignature += \" XX \"\n\t})\n\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/\")\n\n\t// TEST\n\tassert.Equal(t, http.StatusUnauthorized, w.Code)\n\tassert.Equal(t, \"ACD\", signature)\n}"} {"repo":"gin","file":"middleware_test.go","line":185,"symbol":"TestMiddlewareAbortHandlersChainAndNext","kind":"function","lang":"go","code":"func TestMiddlewareAbortHandlersChainAndNext(t *testing.T) {\n\tsignature := \"\"\n\trouter := New()\n\trouter.Use(func(c *Context) {\n\t\tsignature += \"A\"\n\t\tc.Next()\n\t\tc.AbortWithStatus(http.StatusGone)\n\t\tsignature += \"B\"\n\t})\n\trouter.GET(\"/\", func(c *Context) {\n\t\tsignature += \"C\"\n\t\tc.Next()\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/\")\n\n\t// TEST\n\tassert.Equal(t, http.StatusGone, w.Code)\n\tassert.Equal(t, \"ACB\", signature)\n}"} {"repo":"gin","file":"middleware_test.go","line":208,"symbol":"TestMiddlewareFailHandlersChain","kind":"function","lang":"go","doc":"TestMiddlewareFailHandlersChain - ensure that Fail interrupt used middleware in fifo order as as well as Abort","code":"func TestMiddlewareFailHandlersChain(t *testing.T) {\n\t// SETUP\n\tsignature := \"\"\n\trouter := New()\n\trouter.Use(func(context *Context) {\n\t\tsignature += \"A\"\n\t\tcontext.AbortWithError(http.StatusInternalServerError, errors.New(\"foo\")) //nolint: errcheck\n\t})\n\trouter.Use(func(context *Context) {\n\t\tsignature += \"B\"\n\t\tcontext.Next()\n\t\tsignature += \"C\"\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/\")\n\n\t// TEST\n\tassert.Equal(t, http.StatusInternalServerError, w.Code)\n\tassert.Equal(t, \"A\", signature)\n}"} {"repo":"gin","file":"middleware_test.go","line":229,"symbol":"TestMiddlewareWrite","kind":"function","lang":"go","code":"func TestMiddlewareWrite(t *testing.T) {\n\trouter := New()\n\trouter.Use(func(c *Context) {\n\t\tc.String(http.StatusBadRequest, \"hola\\n\")\n\t})\n\trouter.Use(func(c *Context) {\n\t\tc.XML(http.StatusBadRequest, H{\"foo\": \"bar\"})\n\t})\n\trouter.Use(func(c *Context) {\n\t\tc.JSON(http.StatusBadRequest, H{\"foo\": \"bar\"})\n\t})\n\trouter.GET(\"/\", func(c *Context) {\n\t\tc.JSON(http.StatusBadRequest, H{\"foo\": \"bar\"})\n\t}, func(c *Context) {\n\t\tc.Render(http.StatusBadRequest, sse.Event{\n\t\t\tEvent: \"test\",\n\t\t\tData: \"message\",\n\t\t})\n\t})\n\n\tw := PerformRequest(router, http.MethodGet, \"/\")\n\n\tassert.Equal(t, http.StatusBadRequest, w.Code)\n\tassert.Equal(t, strings.ReplaceAll(\"hola\\nbar{\\\"foo\\\":\\\"bar\\\"}{\\\"foo\\\":\\\"bar\\\"}event:test\\ndata:message\\n\\n\", \" \", \"\"), strings.ReplaceAll(w.Body.String(), \" \", \"\"))\n}"} {"repo":"gin","file":"mode.go","line":17,"symbol":"EnvGinMode","kind":"constant","lang":"go","doc":"EnvGinMode indicates environment name for gin mode.","code":"EnvGinMode = \"GIN_MODE\""} {"repo":"gin","file":"mode.go","line":21,"symbol":"DebugMode","kind":"constant","lang":"go","doc":"DebugMode indicates gin mode is debug.","code":"DebugMode = \"debug\""} {"repo":"gin","file":"mode.go","line":23,"symbol":"ReleaseMode","kind":"constant","lang":"go","doc":"ReleaseMode indicates gin mode is release.","code":"ReleaseMode = \"release\""} {"repo":"gin","file":"mode.go","line":25,"symbol":"TestMode","kind":"constant","lang":"go","doc":"TestMode indicates gin mode is test.","code":"TestMode = \"test\""} {"repo":"gin","file":"mode.go","line":29,"symbol":"debugCode","kind":"constant","lang":"go","code":"debugCode = iota"} {"repo":"gin","file":"mode.go","line":30,"symbol":"releaseCode","kind":"constant","lang":"go","code":"releaseCode"} {"repo":"gin","file":"mode.go","line":31,"symbol":"testCode","kind":"constant","lang":"go","code":"testCode"} {"repo":"gin","file":"mode.go","line":42,"symbol":"DefaultWriter","kind":"variable","lang":"go","doc":"Note that both Logger and Recovery provides custom ways to configure their output io.Writer. To support coloring in Windows use: import \"github.com/mattn/go-colorable\" gin.DefaultWriter = colorable.NewColorableStdout()","code":"DefaultWriter io.Writer = os.Stdout"} {"repo":"gin","file":"mode.go","line":45,"symbol":"DefaultErrorWriter","kind":"variable","lang":"go","doc":"DefaultErrorWriter is the default io.Writer used by Gin to debug errors","code":"DefaultErrorWriter io.Writer = os.Stderr"} {"repo":"gin","file":"mode.go","line":48,"symbol":"ginMode","kind":"variable","lang":"go","code":"ginMode int32 = debugCode"} {"repo":"gin","file":"mode.go","line":49,"symbol":"modeName","kind":"variable","lang":"go","code":"modeName atomic.Value"} {"repo":"gin","file":"mode.go","line":52,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tmode := os.Getenv(EnvGinMode)\n\tSetMode(mode)\n}"} {"repo":"gin","file":"mode.go","line":58,"symbol":"SetMode","kind":"function","lang":"go","doc":"SetMode sets gin mode according to input string.","code":"func SetMode(value string) {\n\tif value == \"\" {\n\t\tif flag.Lookup(\"test.v\") != nil {\n\t\t\tvalue = TestMode\n\t\t} else {\n\t\t\tvalue = DebugMode\n\t\t}\n\t}\n\n\tswitch value {\n\tcase DebugMode:\n\t\tatomic.StoreInt32(&ginMode, debugCode)\n\tcase ReleaseMode:\n\t\tatomic.StoreInt32(&ginMode, releaseCode)\n\tcase TestMode:\n\t\tatomic.StoreInt32(&ginMode, testCode)\n\tdefault:\n\t\tpanic(\"gin mode unknown: \" + value + \" (available mode: debug release test)\")\n\t}\n\tmodeName.Store(value)\n}"} {"repo":"gin","file":"mode.go","line":81,"symbol":"DisableBindValidation","kind":"function","lang":"go","doc":"DisableBindValidation closes the default validator.","code":"func DisableBindValidation() {\n\tbinding.Validator = nil\n}"} {"repo":"gin","file":"mode.go","line":87,"symbol":"EnableJsonDecoderUseNumber","kind":"function","lang":"go","doc":"EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to call the UseNumber method on the JSON Decoder instance.","code":"func EnableJsonDecoderUseNumber() {\n\tbinding.EnableDecoderUseNumber = true\n}"} {"repo":"gin","file":"mode.go","line":93,"symbol":"EnableJsonDecoderDisallowUnknownFields","kind":"function","lang":"go","doc":"EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to call the DisallowUnknownFields method on the JSON Decoder instance.","code":"func EnableJsonDecoderDisallowUnknownFields() {\n\tbinding.EnableDecoderDisallowUnknownFields = true\n}"} {"repo":"gin","file":"mode.go","line":98,"symbol":"Mode","kind":"function","lang":"go","doc":"Mode returns current gin mode.","code":"func Mode() string {\n\treturn modeName.Load().(string)\n}"} {"repo":"gin","file":"mode_test.go","line":16,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tos.Setenv(EnvGinMode, TestMode)\n}"} {"repo":"gin","file":"mode_test.go","line":20,"symbol":"TestSetMode","kind":"function","lang":"go","code":"func TestSetMode(t *testing.T) {\n\tassert.Equal(t, int32(testCode), atomic.LoadInt32(&ginMode))\n\tassert.Equal(t, TestMode, Mode())\n\tos.Unsetenv(EnvGinMode)\n\n\tSetMode(\"\")\n\tassert.Equal(t, int32(testCode), atomic.LoadInt32(&ginMode))\n\tassert.Equal(t, TestMode, Mode())\n\n\tSetMode(DebugMode)\n\tassert.Equal(t, int32(debugCode), atomic.LoadInt32(&ginMode))\n\tassert.Equal(t, DebugMode, Mode())\n\n\tSetMode(ReleaseMode)\n\tassert.Equal(t, int32(releaseCode), atomic.LoadInt32(&ginMode))\n\tassert.Equal(t, ReleaseMode, Mode())\n\n\tSetMode(TestMode)\n\tassert.Equal(t, int32(testCode), atomic.LoadInt32(&ginMode))\n\tassert.Equal(t, TestMode, Mode())\n\n\tassert.Panics(t, func() { SetMode(\"unknown\") })\n}"} {"repo":"gin","file":"mode_test.go","line":44,"symbol":"TestDisableBindValidation","kind":"function","lang":"go","code":"func TestDisableBindValidation(t *testing.T) {\n\tv := binding.Validator\n\tassert.NotNil(t, binding.Validator)\n\tDisableBindValidation()\n\tassert.Nil(t, binding.Validator)\n\tbinding.Validator = v\n}"} {"repo":"gin","file":"mode_test.go","line":52,"symbol":"TestEnableJsonDecoderUseNumber","kind":"function","lang":"go","code":"func TestEnableJsonDecoderUseNumber(t *testing.T) {\n\tassert.False(t, binding.EnableDecoderUseNumber)\n\tEnableJsonDecoderUseNumber()\n\tassert.True(t, binding.EnableDecoderUseNumber)\n}"} {"repo":"gin","file":"mode_test.go","line":58,"symbol":"TestEnableJsonDecoderDisallowUnknownFields","kind":"function","lang":"go","code":"func TestEnableJsonDecoderDisallowUnknownFields(t *testing.T) {\n\tassert.False(t, binding.EnableDecoderDisallowUnknownFields)\n\tEnableJsonDecoderDisallowUnknownFields()\n\tassert.True(t, binding.EnableDecoderDisallowUnknownFields)\n}"} {"repo":"gin","file":"path.go","line":8,"symbol":"stackBufSize","kind":"constant","lang":"go","code":"stackBufSize = 128"} {"repo":"gin","file":"path.go","line":23,"symbol":"cleanPath","kind":"function","lang":"go","doc":"3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it. 4. Eliminate .. elements that begin a rooted path: that is, replace \"/..\" by \"/\" at the beginning of a path. If the result of this process is an empty string, \"/\" is returned.","code":"func cleanPath(p string) string {\n\t// Turn empty string into \"/\"\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\n\t// Reasonably sized buffer on stack to avoid allocations in the common case.\n\t// If a larger buffer is required, it gets allocated dynamically.\n\tbuf := make([]byte, 0, stackBufSize)\n\n\tn := len(p)\n\n\t// Invariants:\n\t// reading from path; r is index of next byte to process.\n\t// writing to buf; w is index of next byte to write.\n\n\t// path must start with '/'\n\tr := 1\n\tw := 1\n\n\tif p[0] != '/' {\n\t\tr = 0\n\n\t\tif n+1 > stackBufSize {\n\t\t\tbuf = make([]byte, n+1)\n\t\t} else {\n\t\t\tbuf = buf[:n+1]\n\t\t}\n\t\tbuf[0] = '/'\n\t}\n\n\ttrailing := n > 1 && p[n-1] == '/'\n\n\t// A bit more clunky without a 'lazybuf' like the path package, but the loop\n\t// gets completely inlined (bufApp calls).\n\t// So in contrast to the path package this loop has no expensive function\n\t// calls (except make, if needed).\n\n\tfor r < n {\n\t\tswitch {\n\t\tcase p[r] == '/':\n\t\t\t// empty path element, trailing slash is added after the end\n\t\t\tr++\n\n\t\tcase p[r] == '.' && r+1 == n:\n\t\t\ttrailing = true\n\t\t\tr++\n\n\t\tcase p[r] == '.' && p[r+1] == '/':\n\t\t\t// . element\n\t\t\tr += 2\n\n\t\tcase p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):\n\t\t\t// .. "} {"repo":"gin","file":"path.go","line":128,"symbol":"bufApp","kind":"function","lang":"go","doc":"Internal helper to lazily create a buffer if necessary. Calls to this function get inlined.","code":"func bufApp(buf *[]byte, s string, w int, c byte) {\n\tb := *buf\n\tif len(b) == 0 {\n\t\t// No modification of the original string so far.\n\t\t// If the next character is the same as in the original string, we do\n\t\t// not yet have to allocate a buffer.\n\t\tif s[w] == c {\n\t\t\treturn\n\t\t}\n\n\t\t// Otherwise use either the stack buffer, if it is large enough, or\n\t\t// allocate a new buffer on the heap, and copy all previous characters.\n\t\tlength := len(s)\n\t\tif length > cap(b) {\n\t\t\t*buf = make([]byte, length)\n\t\t} else {\n\t\t\t*buf = (*buf)[:length]\n\t\t}\n\t\tb = *buf\n\n\t\tcopy(b, s[:w])\n\t}\n\tb[w] = c\n}"} {"repo":"gin","file":"path.go","line":155,"symbol":"removeRepeatedChar","kind":"function","lang":"go","doc":"removeRepeatedChar removes multiple consecutive 'char's from a string. if s == \"/a//b///c////\" && char == '/', it returns \"/a/b/c/\"","code":"func removeRepeatedChar(s string, char byte) string {\n\t// Check if there are any consecutive chars\n\thasRepeatedChar := false\n\tfor i := 1; i < len(s); i++ {\n\t\tif s[i] == char && s[i-1] == char {\n\t\t\thasRepeatedChar = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasRepeatedChar {\n\t\treturn s\n\t}\n\n\t// Reasonably sized buffer on stack to avoid allocations in the common case.\n\tbuf := make([]byte, 0, stackBufSize)\n\n\t// Invariants:\n\t// reading from s; r is index of next byte to process.\n\t// writing to buf; w is index of next byte to write.\n\tr := 0\n\tw := 0\n\n\tfor n := len(s); r < n; {\n\t\tif s[r] == char {\n\t\t\t// Write the first char\n\t\t\tbufApp(&buf, s, w, char)\n\t\t\tw++\n\t\t\tr++\n\n\t\t\t// Skip all consecutive chars\n\t\t\tfor r < n && s[r] == char {\n\t\t\t\tr++\n\t\t\t}\n\t\t} else {\n\t\t\t// Copy non-char character\n\t\t\tbufApp(&buf, s, w, s[r])\n\t\t\tw++\n\t\t\tr++\n\t\t}\n\t}\n\n\t// If the original string was not modified (or only shortened at the end),\n\t// return the respective substring of the original string.\n\t// Otherwise, return a new string from the buffer.\n\tif len(buf) == 0 {\n\t\treturn s[:w]\n\t}\n\treturn string(buf[:w])\n}"} {"repo":"gin","file":"path_test.go","line":16,"symbol":"cleanPathTest","kind":"type","lang":"go","code":"type cleanPathTest struct {\n\tpath, result string\n}"} {"repo":"gin","file":"path_test.go","line":20,"symbol":"cleanTests","kind":"variable","lang":"go","code":"cleanTests = []cleanPathTest{\n\t// Already clean\n\t{\"/\", \"/\"},\n\t{\"/abc\", \"/abc\"},\n\t{\"/a/b/c\", \"/a/b/c\"},\n\t{\"/abc/\", \"/abc/\"},\n\t{\"/a/b/c/\", \"/a/b/c/\"},\n\n\t// missing root\n\t{\"\", \"/\"},\n\t{\"a/\", \"/a/\"},\n\t{\"abc\", \"/abc\"},\n\t{\"abc/def\", \"/abc/def\"},\n\t{\"a/b/c\", \"/a/b/c\"},\n\n\t// Remove doubled slash\n\t{\"//\", \"/\"},\n\t{\"/abc//\", \"/abc/\"},\n\t{\"/abc/def//\", \"/abc/def/\"},\n\t{\"/a/b/c//\", \"/a/b/c/\"},\n\t{\"/abc//def//ghi\", \"/abc/def/ghi\"},\n\t{\"//abc\", \"/abc\"},\n\t{\"///abc\", \"/abc\"},\n\t{\"//abc//\", \"/abc/\"},\n\n\t// Remove . elements\n\t{\".\", \"/\"},\n\t{\"./\", \"/\"},\n\t{\"/abc/./def\", \"/abc/def\"},\n\t{\"/./abc/def\", \"/abc/def\"},\n\t{\"/abc/.\", \"/abc/\"},\n\n\t// Remove .. elements\n\t{\"..\", \"/\"},\n\t{\"../\", \"/\"},\n\t{\"../../\", \"/\"},\n\t{\"../..\", \"/\"},\n\t{\"../../abc\", \"/abc\"},\n\t{\"/abc/def/ghi/../jkl\", \"/abc/def/jkl\"},\n\t{\"/abc/def/../ghi/../jkl\", \"/abc/jkl\"},\n\t{\"/abc/def/..\", \"/abc\"},\n\t{\"/abc/def/../..\", \"/\"},\n\t{\"/abc/def/../../..\", \"/\"},\n\t{\"/abc/def/../../..\", \"/\"},\n\t{\"/abc/def/../../../ghi/jkl/../../../mno\", \"/mno\"},\n\n\t// Combinations\n\t{\"abc/./../def\", \"/def\"},\n\t{\"abc//./../def\", \"/def\"},\n\t{\"abc/../../././../def\", \"/def\"},\n}"} {"repo":"gin","file":"path_test.go","line":72,"symbol":"TestPathClean","kind":"function","lang":"go","code":"func TestPathClean(t *testing.T) {\n\tfor _, test := range cleanTests {\n\t\tassert.Equal(t, test.result, cleanPath(test.path))\n\t\tassert.Equal(t, test.result, cleanPath(test.result))\n\t}\n}"} {"repo":"gin","file":"path_test.go","line":79,"symbol":"TestPathCleanMallocs","kind":"function","lang":"go","code":"func TestPathCleanMallocs(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping malloc count in short mode\")\n\t}\n\n\tif runtime.GOMAXPROCS(0) > 1 {\n\t\tt.Skip(\"skipping malloc count; GOMAXPROCS>1\")\n\t}\n\n\tfor _, test := range cleanTests {\n\t\tallocs := testing.AllocsPerRun(100, func() { cleanPath(test.result) })\n\t\tassert.InDelta(t, 0, allocs, 0.01)\n\t}\n}"} {"repo":"gin","file":"path_test.go","line":94,"symbol":"BenchmarkPathClean","kind":"function","lang":"go","code":"func BenchmarkPathClean(b *testing.B) {\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tfor _, test := range cleanTests {\n\t\t\tcleanPath(test.path)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"path_test.go","line":104,"symbol":"genLongPaths","kind":"function","lang":"go","code":"func genLongPaths() (testPaths []cleanPathTest) {\n\tfor i := 1; i <= 1234; i++ {\n\t\tss := strings.Repeat(\"a\", i)\n\n\t\tcorrectPath := \"/\" + ss\n\t\ttestPaths = append(testPaths, cleanPathTest{\n\t\t\tpath: correctPath,\n\t\t\tresult: correctPath,\n\t\t}, cleanPathTest{\n\t\t\tpath: ss,\n\t\t\tresult: correctPath,\n\t\t}, cleanPathTest{\n\t\t\tpath: \"//\" + ss,\n\t\t\tresult: correctPath,\n\t\t}, cleanPathTest{\n\t\t\tpath: \"/\" + ss + \"/b/..\",\n\t\t\tresult: correctPath,\n\t\t})\n\t}\n\treturn\n}"} {"repo":"gin","file":"path_test.go","line":126,"symbol":"TestPathCleanLong","kind":"function","lang":"go","code":"func TestPathCleanLong(t *testing.T) {\n\tcleanTests := genLongPaths()\n\n\tfor _, test := range cleanTests {\n\t\tassert.Equal(t, test.result, cleanPath(test.path))\n\t\tassert.Equal(t, test.result, cleanPath(test.result))\n\t}\n}"} {"repo":"gin","file":"path_test.go","line":135,"symbol":"BenchmarkPathCleanLong","kind":"function","lang":"go","code":"func BenchmarkPathCleanLong(b *testing.B) {\n\tcleanTests := genLongPaths()\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tfor _, test := range cleanTests {\n\t\t\tcleanPath(test.path)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"path_test.go","line":147,"symbol":"TestRemoveRepeatedChar","kind":"function","lang":"go","code":"func TestRemoveRepeatedChar(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\tstr string\n\t\tchar byte\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"empty\",\n\t\t\tstr: \"\",\n\t\t\tchar: 'a',\n\t\t\twant: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"noSlash\",\n\t\t\tstr: \"abc\",\n\t\t\tchar: ',',\n\t\t\twant: \"abc\",\n\t\t},\n\t\t{\n\t\t\tname: \"withSlash\",\n\t\t\tstr: \"/a/b/c/\",\n\t\t\tchar: '/',\n\t\t\twant: \"/a/b/c/\",\n\t\t},\n\t\t{\n\t\t\tname: \"withRepeatedSlashes\",\n\t\t\tstr: \"/a//b///c////\",\n\t\t\tchar: '/',\n\t\t\twant: \"/a/b/c/\",\n\t\t},\n\t\t{\n\t\t\tname: \"threeSlashes\",\n\t\t\tstr: \"///\",\n\t\t\tchar: '/',\n\t\t\twant: \"/\",\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tres := removeRepeatedChar(tc.str, tc.char)\n\t\t\tassert.Equal(t, tc.want, res)\n\t\t})\n\t}\n}"} {"repo":"gin","file":"recovery.go","line":27,"symbol":"dunno","kind":"constant","lang":"go","code":"dunno = \"???\""} {"repo":"gin","file":"recovery.go","line":28,"symbol":"stackSkip","kind":"constant","lang":"go","code":"stackSkip = 3"} {"repo":"gin","file":"recovery.go","line":32,"symbol":"RecoveryFunc","kind":"type","lang":"go","doc":"RecoveryFunc defines the function passable to CustomRecovery.","code":"type RecoveryFunc func(c *Context, err any)"} {"repo":"gin","file":"recovery.go","line":35,"symbol":"Recovery","kind":"function","lang":"go","doc":"Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.","code":"func Recovery() HandlerFunc {\n\treturn RecoveryWithWriter(DefaultErrorWriter)\n}"} {"repo":"gin","file":"recovery.go","line":40,"symbol":"CustomRecovery","kind":"function","lang":"go","doc":"CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it.","code":"func CustomRecovery(handle RecoveryFunc) HandlerFunc {\n\treturn RecoveryWithWriter(DefaultErrorWriter, handle)\n}"} {"repo":"gin","file":"recovery.go","line":45,"symbol":"RecoveryWithWriter","kind":"function","lang":"go","doc":"RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.","code":"func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc {\n\tif len(recovery) > 0 {\n\t\treturn CustomRecoveryWithWriter(out, recovery[0])\n\t}\n\treturn CustomRecoveryWithWriter(out, defaultHandleRecovery)\n}"} {"repo":"gin","file":"recovery.go","line":53,"symbol":"CustomRecoveryWithWriter","kind":"function","lang":"go","doc":"CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.","code":"func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {\n\tvar logger *log.Logger\n\tif out != nil {\n\t\tlogger = log.New(out, \"\\n\\n\\x1b[31m\", log.LstdFlags)\n\t}\n\treturn func(c *Context) {\n\t\tdefer func() {\n\t\t\tif rec := recover(); rec != nil {\n\t\t\t\t// Check for a broken connection, as it is not really a\n\t\t\t\t// condition that warrants a panic stack trace.\n\t\t\t\tvar isBrokenPipe bool\n\t\t\t\terr, ok := rec.(error)\n\t\t\t\tif ok {\n\t\t\t\t\tisBrokenPipe = errors.Is(err, syscall.EPIPE) ||\n\t\t\t\t\t\terrors.Is(err, syscall.ECONNRESET) ||\n\t\t\t\t\t\terrors.Is(err, http.ErrAbortHandler)\n\t\t\t\t}\n\t\t\t\tif logger != nil {\n\t\t\t\t\tif isBrokenPipe {\n\t\t\t\t\t\tlogger.Printf(\"%s\\n%s%s\", rec, secureRequestDump(c.Request), reset)\n\t\t\t\t\t} else if IsDebugging() {\n\t\t\t\t\t\tlogger.Printf(\"[Recovery] %s panic recovered:\\n%s\\n%s\\n%s%s\",\n\t\t\t\t\t\t\ttimeFormat(time.Now()), secureRequestDump(c.Request), rec, stack(stackSkip), reset)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.Printf(\"[Recovery] %s panic recovered:\\n%s\\n%s%s\",\n\t\t\t\t\t\t\ttimeFormat(time.Now()), rec, stack(stackSkip), reset)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif isBrokenPipe {\n\t\t\t\t\t// If the connection is dead, we can't write a status to it.\n\t\t\t\t\tc.Error(err) //nolint: errcheck\n\t\t\t\t\tc.Abort()\n\t\t\t\t} else {\n\t\t"} {"repo":"gin","file":"recovery.go","line":54,"symbol":"logger","kind":"variable","lang":"go","code":"logger *log.Logger"} {"repo":"gin","file":"recovery.go","line":63,"symbol":"isBrokenPipe","kind":"variable","lang":"go","doc":"Check for a broken connection, as it is not really a condition that warrants a panic stack trace.","code":"isBrokenPipe bool"} {"repo":"gin","file":"recovery.go","line":98,"symbol":"secureRequestDump","kind":"function","lang":"go","doc":"secureRequestDump returns a sanitized HTTP request dump where the Authorization header, if present, is replaced with a masked value (\"Authorization: *\") to avoid leaking sensitive credentials. Currently, only the Authorization header is sanitized. All other headers and request data remain unchanged.","code":"func secureRequestDump(r *http.Request) string {\n\thttpRequest, _ := httputil.DumpRequest(r, false)\n\tlines := strings.Split(bytesconv.BytesToString(httpRequest), \"\\r\\n\")\n\tfor i, line := range lines {\n\t\tif strings.HasPrefix(line, \"Authorization:\") {\n\t\t\tlines[i] = \"Authorization: *\"\n\t\t}\n\t}\n\treturn strings.Join(lines, \"\\r\\n\")\n}"} {"repo":"gin","file":"recovery.go","line":109,"symbol":"defaultHandleRecovery","kind":"function","lang":"go","code":"func defaultHandleRecovery(c *Context, err any) {\n\te, ok := err.(error)\n\tif !ok {\n\t\te = fmt.Errorf(\"%v\", err)\n\t}\n\tc.Error(e) //nolint: errcheck\n\tc.AbortWithStatus(http.StatusInternalServerError)\n}"} {"repo":"gin","file":"recovery.go","line":119,"symbol":"stack","kind":"function","lang":"go","doc":"stack returns a nicely formatted stack frame, skipping skip frames.","code":"func stack(skip int) []byte {\n\tbuf := new(bytes.Buffer) // the returned data\n\t// As we loop, we open files and read them. These variables record the currently\n\t// loaded file.\n\tvar (\n\t\tnLine string\n\t\tlastFile string\n\t\terr error\n\t)\n\tfor i := skip; ; i++ { // Skip the expected number of frames\n\t\tpc, file, line, ok := runtime.Caller(i)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\t// Print this much at least. If we can't find the source, it won't show.\n\t\tfmt.Fprintf(buf, \"%s:%d (0x%x)\\n\", file, line, pc)\n\t\tif file != lastFile {\n\t\t\tnLine, err = readNthLine(file, line-1)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlastFile = file\n\t\t}\n\t\tfmt.Fprintf(buf, \"\\t%s: %s\\n\", function(pc), cmp.Or(nLine, dunno))\n\t}\n\treturn buf.Bytes()\n}"} {"repo":"gin","file":"recovery.go","line":124,"symbol":"nLine","kind":"variable","lang":"go","code":"nLine string"} {"repo":"gin","file":"recovery.go","line":125,"symbol":"lastFile","kind":"variable","lang":"go","code":"lastFile string"} {"repo":"gin","file":"recovery.go","line":126,"symbol":"err","kind":"variable","lang":"go","code":"err error"} {"repo":"gin","file":"recovery.go","line":151,"symbol":"readNthLine","kind":"function","lang":"go","doc":"readNthLine reads the nth line from the file. It returns the trimmed content of the line if found, or an empty string if the line doesn't exist. If there's an error opening the file, it returns the error.","code":"func readNthLine(file string, n int) (string, error) {\n\tif n < 0 {\n\t\treturn \"\", nil\n\t}\n\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor i := 0; i < n; i++ {\n\t\tif !scanner.Scan() {\n\t\t\treturn \"\", nil\n\t\t}\n\t}\n\n\tif scanner.Scan() {\n\t\treturn strings.TrimSpace(scanner.Text()), nil\n\t}\n\n\treturn \"\", nil\n}"} {"repo":"gin","file":"recovery.go","line":177,"symbol":"function","kind":"function","lang":"go","doc":"function returns, if possible, the name of the function containing the PC.","code":"func function(pc uintptr) string {\n\tfn := runtime.FuncForPC(pc)\n\tif fn == nil {\n\t\treturn dunno\n\t}\n\tname := fn.Name()\n\t// The name includes the path name to the package, which is unnecessary\n\t// since the file name is already included. Plus, it has center dots.\n\t// That is, we see\n\t//\truntime/debug.*T·ptrmethod\n\t// and want\n\t//\t*T.ptrmethod\n\t// Also the package path might contain dot (e.g. code.google.com/...),\n\t// so first eliminate the path prefix\n\tif lastSlash := strings.LastIndexByte(name, '/'); lastSlash >= 0 {\n\t\tname = name[lastSlash+1:]\n\t}\n\tif period := strings.IndexByte(name, '.'); period >= 0 {\n\t\tname = name[period+1:]\n\t}\n\tname = strings.ReplaceAll(name, \"·\", \".\")\n\treturn name\n}"} {"repo":"gin","file":"recovery.go","line":202,"symbol":"timeFormat","kind":"function","lang":"go","doc":"timeFormat returns a customized time string for logger.","code":"func timeFormat(t time.Time) string {\n\treturn t.Format(\"2006/01/02 - 15:04:05\")\n}"} {"repo":"gin","file":"recovery_test.go","line":19,"symbol":"TestPanicClean","kind":"function","lang":"go","code":"func TestPanicClean(t *testing.T) {\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\tpassword := \"my-super-secret-password\"\n\trouter.Use(RecoveryWithWriter(buffer))\n\trouter.GET(\"/recovery\", func(c *Context) {\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t\tpanic(\"Oops, Houston, we have a problem\")\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/recovery\",\n\t\theader{\n\t\t\tKey: \"Host\",\n\t\t\tValue: \"www.google.com\",\n\t\t},\n\t\theader{\n\t\t\tKey: \"Authorization\",\n\t\t\tValue: \"Bearer \" + password,\n\t\t},\n\t\theader{\n\t\t\tKey: \"Content-Type\",\n\t\t\tValue: \"application/json\",\n\t\t},\n\t)\n\t// TEST\n\tassert.Equal(t, http.StatusBadRequest, w.Code)\n\n\t// Check the buffer does not have the secret key\n\tassert.NotContains(t, buffer.String(), password)\n}"} {"repo":"gin","file":"recovery_test.go","line":51,"symbol":"TestPanicInHandler","kind":"function","lang":"go","doc":"TestPanicInHandler assert that panic has been recovered.","code":"func TestPanicInHandler(t *testing.T) {\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\trouter.Use(RecoveryWithWriter(buffer))\n\trouter.GET(\"/recovery\", func(_ *Context) {\n\t\tpanic(\"Oops, Houston, we have a problem\")\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusInternalServerError, w.Code)\n\tassert.Contains(t, buffer.String(), \"panic recovered\")\n\tassert.Contains(t, buffer.String(), \"Oops, Houston, we have a problem\")\n\tassert.Contains(t, buffer.String(), t.Name())\n\tassert.NotContains(t, buffer.String(), \"GET /recovery\")\n\n\t// Debug mode prints the request\n\tSetMode(DebugMode)\n\t// RUN\n\tw = PerformRequest(router, http.MethodGet, \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusInternalServerError, w.Code)\n\tassert.Contains(t, buffer.String(), \"GET /recovery\")\n\n\tSetMode(TestMode)\n}"} {"repo":"gin","file":"recovery_test.go","line":79,"symbol":"TestPanicWithAbort","kind":"function","lang":"go","doc":"TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.","code":"func TestPanicWithAbort(t *testing.T) {\n\trouter := New()\n\trouter.Use(RecoveryWithWriter(nil))\n\trouter.GET(\"/recovery\", func(c *Context) {\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t\tpanic(\"Oops, Houston, we have a problem\")\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusBadRequest, w.Code)\n}"} {"repo":"gin","file":"recovery_test.go","line":92,"symbol":"TestFunction","kind":"function","lang":"go","code":"func TestFunction(t *testing.T) {\n\tbs := function(1)\n\tassert.Equal(t, dunno, bs)\n}"} {"repo":"gin","file":"recovery_test.go","line":99,"symbol":"TestPanicWithBrokenPipe","kind":"function","lang":"go","doc":"TestPanicWithBrokenPipe asserts that recovery specifically handles writing responses to broken pipes","code":"func TestPanicWithBrokenPipe(t *testing.T) {\n\tconst expectCode = 204\n\n\texpectErrnos := []syscall.Errno{\n\t\tsyscall.EPIPE,\n\t\tsyscall.ECONNRESET,\n\t}\n\n\tfor _, errno := range expectErrnos {\n\t\tt.Run(\"Recovery from \"+errno.Error(), func(t *testing.T) {\n\t\t\tvar buf strings.Builder\n\n\t\t\trouter := New()\n\t\t\trouter.Use(RecoveryWithWriter(&buf))\n\t\t\trouter.GET(\"/recovery\", func(c *Context) {\n\t\t\t\t// Start writing response\n\t\t\t\tc.Header(\"X-Test\", \"Value\")\n\t\t\t\tc.Status(expectCode)\n\n\t\t\t\t// Oops. Client connection closed\n\t\t\t\te := &net.OpError{Err: &os.SyscallError{Err: errno}}\n\t\t\t\tpanic(e)\n\t\t\t})\n\t\t\t// RUN\n\t\t\tw := PerformRequest(router, http.MethodGet, \"/recovery\")\n\t\t\t// TEST\n\t\t\tassert.Equal(t, expectCode, w.Code)\n\t\t\tassert.Contains(t, strings.ToLower(buf.String()), errno.Error())\n\t\t\tassert.NotContains(t, strings.ToLower(buf.String()), \"[Recovery]\")\n\t\t})\n\t}\n}"} {"repo":"gin","file":"recovery_test.go","line":100,"symbol":"expectCode","kind":"constant","lang":"go","code":"expectCode = 204"} {"repo":"gin","file":"recovery_test.go","line":109,"symbol":"buf","kind":"variable","lang":"go","code":"buf strings.Builder"} {"repo":"gin","file":"recovery_test.go","line":133,"symbol":"TestPanicWithAbortHandler","kind":"function","lang":"go","doc":"TestPanicWithAbortHandler asserts that recovery handles http.ErrAbortHandler as broken pipe","code":"func TestPanicWithAbortHandler(t *testing.T) {\n\tconst expectCode = 204\n\n\tvar buf strings.Builder\n\trouter := New()\n\trouter.Use(RecoveryWithWriter(&buf))\n\trouter.GET(\"/recovery\", func(c *Context) {\n\t\t// Start writing response\n\t\tc.Header(\"X-Test\", \"Value\")\n\t\tc.Status(expectCode)\n\n\t\t// Panic with ErrAbortHandler which should be treated as broken pipe\n\t\tpanic(http.ErrAbortHandler)\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/recovery\")\n\t// TEST\n\tassert.Equal(t, expectCode, w.Code)\n\tout := buf.String()\n\tassert.Contains(t, out, \"net/http: abort Handler\")\n\tassert.NotContains(t, out, \"panic recovered\")\n}"} {"repo":"gin","file":"recovery_test.go","line":134,"symbol":"expectCode","kind":"constant","lang":"go","code":"expectCode = 204"} {"repo":"gin","file":"recovery_test.go","line":136,"symbol":"buf","kind":"variable","lang":"go","code":"buf strings.Builder"} {"repo":"gin","file":"recovery_test.go","line":156,"symbol":"TestPanicInHandlerRecordsError","kind":"function","lang":"go","code":"func TestPanicInHandlerRecordsError(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\trecoveredErr any\n\t\texpectedErr string\n\t}{\n\t\t{\n\t\t\tname: \"string panic\",\n\t\t\trecoveredErr: \"Oops, Houston, we have a problem\",\n\t\t\texpectedErr: \"Oops, Houston, we have a problem\",\n\t\t},\n\t\t{\n\t\t\tname: \"error panic\",\n\t\t\trecoveredErr: errors.New(\"recovered error\"),\n\t\t\texpectedErr: \"recovered error\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trouter := New()\n\n\t\t\tvar recoveredErrors errorMsgs\n\t\t\trouter.Use(func(c *Context) {\n\t\t\t\tc.Next()\n\t\t\t\trecoveredErrors = c.Errors\n\t\t\t})\n\t\t\trouter.Use(RecoveryWithWriter(nil))\n\t\t\trouter.GET(\"/recovery\", func(_ *Context) {\n\t\t\t\tpanic(tt.recoveredErr)\n\t\t\t})\n\n\t\t\tw := PerformRequest(router, http.MethodGet, \"/recovery\")\n\n\t\t\tassert.Equal(t, http.StatusInternalServerError, w.Code)\n\t\t\tif assert.Len(t, recoveredErrors, 1) {\n\t\t\t\tassert.EqualError(t, recoveredErrors[0], tt.expectedErr)\n\t\t\t\tassert.Equal(t, ErrorTypePrivate, recoveredErrors[0].Type)\n\t\t\t}\n\t\t})\n\t}\n}"} {"repo":"gin","file":"recovery_test.go","line":178,"symbol":"recoveredErrors","kind":"variable","lang":"go","code":"recoveredErrors errorMsgs"} {"repo":"gin","file":"recovery_test.go","line":199,"symbol":"TestCustomRecoveryWithWriter","kind":"function","lang":"go","code":"func TestCustomRecoveryWithWriter(t *testing.T) {\n\terrBuffer := new(strings.Builder)\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\thandleRecovery := func(c *Context, err any) {\n\t\terrBuffer.WriteString(err.(string))\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t}\n\trouter.Use(CustomRecoveryWithWriter(buffer, handleRecovery))\n\trouter.GET(\"/recovery\", func(_ *Context) {\n\t\tpanic(\"Oops, Houston, we have a problem\")\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusBadRequest, w.Code)\n\tassert.Contains(t, buffer.String(), \"panic recovered\")\n\tassert.Contains(t, buffer.String(), \"Oops, Houston, we have a problem\")\n\tassert.Contains(t, buffer.String(), t.Name())\n\tassert.NotContains(t, buffer.String(), \"GET /recovery\")\n\n\t// Debug mode prints the request\n\tSetMode(DebugMode)\n\t// RUN\n\tw = PerformRequest(router, http.MethodGet, \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusBadRequest, w.Code)\n\tassert.Contains(t, buffer.String(), \"GET /recovery\")\n\n\tassert.Equal(t, strings.Repeat(\"Oops, Houston, we have a problem\", 2), errBuffer.String())\n\n\tSetMode(TestMode)\n}"} {"repo":"gin","file":"recovery_test.go","line":233,"symbol":"TestCustomRecovery","kind":"function","lang":"go","code":"func TestCustomRecovery(t *testing.T) {\n\terrBuffer := new(strings.Builder)\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\tDefaultErrorWriter = buffer\n\thandleRecovery := func(c *Context, err any) {\n\t\terrBuffer.WriteString(err.(string))\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t}\n\trouter.Use(CustomRecovery(handleRecovery))\n\trouter.GET(\"/recovery\", func(_ *Context) {\n\t\tpanic(\"Oops, Houston, we have a problem\")\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusBadRequest, w.Code)\n\tassert.Contains(t, buffer.String(), \"panic recovered\")\n\tassert.Contains(t, buffer.String(), \"Oops, Houston, we have a problem\")\n\tassert.Contains(t, buffer.String(), t.Name())\n\tassert.NotContains(t, buffer.String(), \"GET /recovery\")\n\n\t// Debug mode prints the request\n\tSetMode(DebugMode)\n\t// RUN\n\tw = PerformRequest(router, http.MethodGet, \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusBadRequest, w.Code)\n\tassert.Contains(t, buffer.String(), \"GET /recovery\")\n\n\tassert.Equal(t, strings.Repeat(\"Oops, Houston, we have a problem\", 2), errBuffer.String())\n\n\tSetMode(TestMode)\n}"} {"repo":"gin","file":"recovery_test.go","line":268,"symbol":"TestRecoveryWithWriterWithCustomRecovery","kind":"function","lang":"go","code":"func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) {\n\terrBuffer := new(strings.Builder)\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\tDefaultErrorWriter = buffer\n\thandleRecovery := func(c *Context, err any) {\n\t\terrBuffer.WriteString(err.(string))\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t}\n\trouter.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery))\n\trouter.GET(\"/recovery\", func(_ *Context) {\n\t\tpanic(\"Oops, Houston, we have a problem\")\n\t})\n\t// RUN\n\tw := PerformRequest(router, http.MethodGet, \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusBadRequest, w.Code)\n\tassert.Contains(t, buffer.String(), \"panic recovered\")\n\tassert.Contains(t, buffer.String(), \"Oops, Houston, we have a problem\")\n\tassert.Contains(t, buffer.String(), t.Name())\n\tassert.NotContains(t, buffer.String(), \"GET /recovery\")\n\n\t// Debug mode prints the request\n\tSetMode(DebugMode)\n\t// RUN\n\tw = PerformRequest(router, http.MethodGet, \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusBadRequest, w.Code)\n\tassert.Contains(t, buffer.String(), \"GET /recovery\")\n\n\tassert.Equal(t, strings.Repeat(\"Oops, Houston, we have a problem\", 2), errBuffer.String())\n\n\tSetMode(TestMode)\n}"} {"repo":"gin","file":"recovery_test.go","line":303,"symbol":"TestSecureRequestDump","kind":"function","lang":"go","code":"func TestSecureRequestDump(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\treq *http.Request\n\t\twantContains string\n\t\twantNotContain string\n\t}{\n\t\t{\n\t\t\tname: \"Authorization header standard case\",\n\t\t\treq: func() *http.Request {\n\t\t\t\tr, _ := http.NewRequest(http.MethodGet, \"http://example.com\", nil)\n\t\t\t\tr.Header.Set(\"Authorization\", \"Bearer secret-token\")\n\t\t\t\treturn r\n\t\t\t}(),\n\t\t\twantContains: \"Authorization: *\",\n\t\t\twantNotContain: \"Bearer secret-token\",\n\t\t},\n\t\t{\n\t\t\tname: \"authorization header lowercase\",\n\t\t\treq: func() *http.Request {\n\t\t\t\tr, _ := http.NewRequest(http.MethodGet, \"http://example.com\", nil)\n\t\t\t\tr.Header.Set(\"authorization\", \"some-secret\")\n\t\t\t\treturn r\n\t\t\t}(),\n\t\t\twantContains: \"Authorization: *\",\n\t\t\twantNotContain: \"some-secret\",\n\t\t},\n\t\t{\n\t\t\tname: \"Authorization header mixed case\",\n\t\t\treq: func() *http.Request {\n\t\t\t\tr, _ := http.NewRequest(http.MethodGet, \"http://example.com\", nil)\n\t\t\t\tr.Header.Set(\"AuThOrIzAtIoN\", \"token123\")\n\t\t\t\treturn r\n\t\t\t}(),\n\t\t\twantContains: \"Authorization: *\",\n\t\t\twantNotContain: \"token123\",\n\t\t},\n\t\t{\n\t\t\tname: \"No Authorization header\",\n\t\t\treq: func() *http.Request {\n\t\t\t\tr, _ := http.NewRequest(http.MethodGet, \"http://"} {"repo":"gin","file":"recovery_test.go","line":366,"symbol":"TestReadNthLine","kind":"function","lang":"go","doc":"TestReadNthLine tests the readNthLine function with various scenarios.","code":"func TestReadNthLine(t *testing.T) {\n\t// Create a temporary test file\n\ttestContent := \"line 0 \\n line 1 \\nline 2 \\nline 3 \\nline 4\"\n\ttempFile, err := os.CreateTemp(\"\", \"testfile*.txt\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(tempFile.Name())\n\n\t// Write test content to the temporary file\n\tif _, err := tempFile.WriteString(testContent); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := tempFile.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Test cases\n\ttests := []struct {\n\t\tname string\n\t\tlineNum int\n\t\tfileName string\n\t\twant string\n\t\twantErr bool\n\t}{\n\t\t{name: \"Read first line\", lineNum: 0, fileName: tempFile.Name(), want: \"line 0\", wantErr: false},\n\t\t{name: \"Read middle line\", lineNum: 2, fileName: tempFile.Name(), want: \"line 2\", wantErr: false},\n\t\t{name: \"Read last line\", lineNum: 4, fileName: tempFile.Name(), want: \"line 4\", wantErr: false},\n\t\t{name: \"Line number exceeds file length\", lineNum: 10, fileName: tempFile.Name(), want: \"\", wantErr: false},\n\t\t{name: \"Negative line number\", lineNum: -1, fileName: tempFile.Name(), want: \"\", wantErr: false},\n\t\t{name: \"Non-existent file\", lineNum: 1, fileName: \"/non/existent/file.txt\", want: \"\", wantErr: true},\n\t}\n\n\tfor _, tt :="} {"repo":"gin","file":"recovery_test.go","line":408,"symbol":"BenchmarkStack","kind":"function","lang":"go","code":"func BenchmarkStack(b *testing.B) {\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\t_ = stack(stackSkip)\n\t}\n}"} {"repo":"gin","file":"render/bson.go","line":14,"symbol":"BSON","kind":"type","lang":"go","doc":"BSON contains the given interface object.","code":"type BSON struct {\n\tData any\n}"} {"repo":"gin","file":"render/bson.go","line":18,"symbol":"bsonContentType","kind":"variable","lang":"go","code":"bsonContentType = []string{\"application/bson\"}"} {"repo":"gin","file":"render/bson.go","line":21,"symbol":"Render","kind":"method","lang":"go","doc":"Render (BSON) marshals the given interface object and writes data with custom ContentType.","code":"func (r BSON) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\n\tbytes, err := bson.Marshal(&r.Data)\n\tif err == nil {\n\t\t_, err = w.Write(bytes)\n\t}\n\treturn err\n}"} {"repo":"gin","file":"render/bson.go","line":32,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (BSONBuf) writes BSONBuf ContentType.","code":"func (r BSON) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, bsonContentType)\n}"} {"repo":"gin","file":"render/data.go","line":13,"symbol":"Data","kind":"type","lang":"go","doc":"Data contains ContentType and bytes data.","code":"type Data struct {\n\tContentType string\n\tData []byte\n}"} {"repo":"gin","file":"render/data.go","line":19,"symbol":"Render","kind":"method","lang":"go","doc":"Render (Data) writes data with custom ContentType.","code":"func (r Data) Render(w http.ResponseWriter) (err error) {\n\tr.WriteContentType(w)\n\tif len(r.Data) > 0 {\n\t\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(r.Data)))\n\t}\n\t_, err = w.Write(r.Data)\n\treturn\n}"} {"repo":"gin","file":"render/data.go","line":29,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (Data) writes custom ContentType.","code":"func (r Data) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, []string{r.ContentType})\n}"} {"repo":"gin","file":"render/html.go","line":16,"symbol":"Delims","kind":"type","lang":"go","doc":"Delims represents a set of Left and Right delimiters for HTML template rendering.","code":"type Delims struct {\n\t// Left delimiter, defaults to {{.\n\tLeft string\n\t// Right delimiter, defaults to }}.\n\tRight string\n}"} {"repo":"gin","file":"render/html.go","line":24,"symbol":"HTMLRender","kind":"type","lang":"go","doc":"HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug.","code":"type HTMLRender interface {\n\t// Instance returns an HTML instance.\n\tInstance(string, any) Render\n}"} {"repo":"gin","file":"render/html.go","line":30,"symbol":"HTMLProduction","kind":"type","lang":"go","doc":"HTMLProduction contains template reference and its delims.","code":"type HTMLProduction struct {\n\tTemplate *template.Template\n\tDelims Delims\n}"} {"repo":"gin","file":"render/html.go","line":36,"symbol":"HTMLDebug","kind":"type","lang":"go","doc":"HTMLDebug contains template delims and pattern and function with file list.","code":"type HTMLDebug struct {\n\tFiles []string\n\tGlob string\n\tFileSystem http.FileSystem\n\tPatterns []string\n\tDelims Delims\n\tFuncMap template.FuncMap\n}"} {"repo":"gin","file":"render/html.go","line":46,"symbol":"HTML","kind":"type","lang":"go","doc":"HTML contains template reference and its name with given interface object.","code":"type HTML struct {\n\tTemplate *template.Template\n\tName string\n\tData any\n}"} {"repo":"gin","file":"render/html.go","line":52,"symbol":"htmlContentType","kind":"variable","lang":"go","code":"htmlContentType = []string{\"text/html; charset=utf-8\"}"} {"repo":"gin","file":"render/html.go","line":54,"symbol":"errHTMLRendererNotConfigured","kind":"variable","lang":"go","code":"errHTMLRendererNotConfigured = errors.New(\"html renderer is not configured\")"} {"repo":"gin","file":"render/html.go","line":57,"symbol":"Instance","kind":"method","lang":"go","doc":"Instance (HTMLProduction) returns an HTML instance which it realizes Render interface.","code":"func (r HTMLProduction) Instance(name string, data any) Render {\n\treturn HTML{\n\t\tTemplate: r.Template,\n\t\tName: name,\n\t\tData: data,\n\t}\n}"} {"repo":"gin","file":"render/html.go","line":66,"symbol":"Instance","kind":"method","lang":"go","doc":"Instance (HTMLDebug) returns an HTML instance which it realizes Render interface.","code":"func (r HTMLDebug) Instance(name string, data any) Render {\n\treturn HTML{\n\t\tTemplate: r.loadTemplate(),\n\t\tName: name,\n\t\tData: data,\n\t}\n}"} {"repo":"gin","file":"render/html.go","line":74,"symbol":"loadTemplate","kind":"method","lang":"go","code":"func (r HTMLDebug) loadTemplate() *template.Template {\n\tif r.FuncMap == nil {\n\t\tr.FuncMap = template.FuncMap{}\n\t}\n\tif len(r.Files) > 0 {\n\t\treturn template.Must(template.New(\"\").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...))\n\t}\n\tif r.Glob != \"\" {\n\t\treturn template.Must(template.New(\"\").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob))\n\t}\n\tif r.FileSystem != nil && len(r.Patterns) > 0 {\n\t\treturn template.Must(template.New(\"\").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFS(\n\t\t\tfs.FileSystem{FileSystem: r.FileSystem}, r.Patterns...))\n\t}\n\tpanic(\"the HTML debug render was created without files or glob pattern or file system with patterns\")\n}"} {"repo":"gin","file":"render/html.go","line":92,"symbol":"Render","kind":"method","lang":"go","doc":"Render (HTML) executes template and writes its result with custom ContentType for response.","code":"func (r HTML) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\tif r.Template == nil {\n\t\treturn errHTMLRendererNotConfigured\n\t}\n\n\tif r.Name == \"\" {\n\t\treturn r.Template.Execute(w, r.Data)\n\t}\n\treturn r.Template.ExecuteTemplate(w, r.Name, r.Data)\n}"} {"repo":"gin","file":"render/html.go","line":105,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (HTML) writes HTML ContentType.","code":"func (r HTML) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, htmlContentType)\n}"} {"repo":"gin","file":"render/json.go","line":19,"symbol":"JSON","kind":"type","lang":"go","doc":"JSON contains the given interface object.","code":"type JSON struct {\n\tData any\n}"} {"repo":"gin","file":"render/json.go","line":24,"symbol":"IndentedJSON","kind":"type","lang":"go","doc":"IndentedJSON contains the given interface object.","code":"type IndentedJSON struct {\n\tData any\n}"} {"repo":"gin","file":"render/json.go","line":29,"symbol":"SecureJSON","kind":"type","lang":"go","doc":"SecureJSON contains the given interface object and its prefix.","code":"type SecureJSON struct {\n\tPrefix string\n\tData any\n}"} {"repo":"gin","file":"render/json.go","line":35,"symbol":"JsonpJSON","kind":"type","lang":"go","doc":"JsonpJSON contains the given interface object its callback.","code":"type JsonpJSON struct {\n\tCallback string\n\tData any\n}"} {"repo":"gin","file":"render/json.go","line":41,"symbol":"AsciiJSON","kind":"type","lang":"go","doc":"AsciiJSON contains the given interface object.","code":"type AsciiJSON struct {\n\tData any\n}"} {"repo":"gin","file":"render/json.go","line":46,"symbol":"PureJSON","kind":"type","lang":"go","doc":"PureJSON contains the given interface object.","code":"type PureJSON struct {\n\tData any\n}"} {"repo":"gin","file":"render/json.go","line":51,"symbol":"jsonContentType","kind":"variable","lang":"go","code":"jsonContentType = []string{\"application/json; charset=utf-8\"}"} {"repo":"gin","file":"render/json.go","line":52,"symbol":"jsonpContentType","kind":"variable","lang":"go","code":"jsonpContentType = []string{\"application/javascript; charset=utf-8\"}"} {"repo":"gin","file":"render/json.go","line":53,"symbol":"jsonASCIIContentType","kind":"variable","lang":"go","code":"jsonASCIIContentType = []string{\"application/json\"}"} {"repo":"gin","file":"render/json.go","line":57,"symbol":"Render","kind":"method","lang":"go","doc":"Render (JSON) writes data with custom ContentType.","code":"func (r JSON) Render(w http.ResponseWriter) error {\n\treturn WriteJSON(w, r.Data)\n}"} {"repo":"gin","file":"render/json.go","line":62,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (JSON) writes JSON ContentType.","code":"func (r JSON) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, jsonContentType)\n}"} {"repo":"gin","file":"render/json.go","line":67,"symbol":"WriteJSON","kind":"function","lang":"go","doc":"WriteJSON marshals the given interface object and writes it with custom ContentType.","code":"func WriteJSON(w http.ResponseWriter, obj any) error {\n\twriteContentType(w, jsonContentType)\n\tjsonBytes, err := json.API.Marshal(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(jsonBytes)\n\treturn err\n}"} {"repo":"gin","file":"render/json.go","line":78,"symbol":"Render","kind":"method","lang":"go","doc":"Render (IndentedJSON) marshals the given interface object and writes it with custom ContentType.","code":"func (r IndentedJSON) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\tjsonBytes, err := json.API.MarshalIndent(r.Data, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(jsonBytes)\n\treturn err\n}"} {"repo":"gin","file":"render/json.go","line":89,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (IndentedJSON) writes JSON ContentType.","code":"func (r IndentedJSON) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, jsonContentType)\n}"} {"repo":"gin","file":"render/json.go","line":94,"symbol":"Render","kind":"method","lang":"go","doc":"Render (SecureJSON) marshals the given interface object and writes it with custom ContentType.","code":"func (r SecureJSON) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\tjsonBytes, err := json.API.Marshal(r.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// if the jsonBytes is array values\n\tif bytes.HasPrefix(jsonBytes, bytesconv.StringToBytes(\"[\")) && bytes.HasSuffix(jsonBytes,\n\t\tbytesconv.StringToBytes(\"]\")) {\n\t\tif _, err = w.Write(bytesconv.StringToBytes(r.Prefix)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t_, err = w.Write(jsonBytes)\n\treturn err\n}"} {"repo":"gin","file":"render/json.go","line":112,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (SecureJSON) writes JSON ContentType.","code":"func (r SecureJSON) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, jsonContentType)\n}"} {"repo":"gin","file":"render/json.go","line":117,"symbol":"Render","kind":"method","lang":"go","doc":"Render (JsonpJSON) marshals the given interface object and writes it and its callback with custom ContentType.","code":"func (r JsonpJSON) Render(w http.ResponseWriter) (err error) {\n\tr.WriteContentType(w)\n\tret, err := json.API.Marshal(r.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif r.Callback == \"\" {\n\t\t_, err = w.Write(ret)\n\t\treturn err\n\t}\n\n\tcallback := template.JSEscapeString(r.Callback)\n\tif _, err = w.Write(bytesconv.StringToBytes(callback)); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = w.Write(bytesconv.StringToBytes(\"(\")); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = w.Write(ret); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err = w.Write(bytesconv.StringToBytes(\");\")); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"} {"repo":"gin","file":"render/json.go","line":150,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (JsonpJSON) writes Javascript ContentType.","code":"func (r JsonpJSON) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, jsonpContentType)\n}"} {"repo":"gin","file":"render/json.go","line":155,"symbol":"Render","kind":"method","lang":"go","doc":"Render (AsciiJSON) marshals the given interface object and writes it with custom ContentType.","code":"func (r AsciiJSON) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\tret, err := json.API.Marshal(r.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar buffer bytes.Buffer\n\tescapeBuf := make([]byte, 0, 6) // Preallocate 6 bytes for Unicode escape sequences\n\n\tfor _, r := range bytesconv.BytesToString(ret) {\n\t\tif r > unicode.MaxASCII {\n\t\t\tescapeBuf = fmt.Appendf(escapeBuf[:0], \"\\\\u%04x\", r) // Reuse escapeBuf\n\t\t\tbuffer.Write(escapeBuf)\n\t\t} else {\n\t\t\tbuffer.WriteByte(byte(r))\n\t\t}\n\t}\n\n\t_, err = w.Write(buffer.Bytes())\n\treturn err\n}"} {"repo":"gin","file":"render/json.go","line":162,"symbol":"buffer","kind":"variable","lang":"go","code":"buffer bytes.Buffer"} {"repo":"gin","file":"render/json.go","line":179,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (AsciiJSON) writes JSON ContentType.","code":"func (r AsciiJSON) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, jsonASCIIContentType)\n}"} {"repo":"gin","file":"render/json.go","line":184,"symbol":"Render","kind":"method","lang":"go","doc":"Render (PureJSON) writes custom ContentType and encodes the given interface object.","code":"func (r PureJSON) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\tencoder := json.API.NewEncoder(w)\n\tencoder.SetEscapeHTML(false)\n\treturn encoder.Encode(r.Data)\n}"} {"repo":"gin","file":"render/json.go","line":192,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (PureJSON) writes custom ContentType.","code":"func (r PureJSON) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, jsonContentType)\n}"} {"repo":"gin","file":"render/msgpack.go","line":18,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = MsgPack{}"} {"repo":"gin","file":"render/msgpack.go","line":22,"symbol":"MsgPack","kind":"type","lang":"go","doc":"MsgPack contains the given interface object.","code":"type MsgPack struct {\n\tData any\n}"} {"repo":"gin","file":"render/msgpack.go","line":26,"symbol":"msgpackContentType","kind":"variable","lang":"go","code":"msgpackContentType = []string{\"application/msgpack; charset=utf-8\"}"} {"repo":"gin","file":"render/msgpack.go","line":29,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (MsgPack) writes MsgPack ContentType.","code":"func (r MsgPack) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, msgpackContentType)\n}"} {"repo":"gin","file":"render/msgpack.go","line":34,"symbol":"Render","kind":"method","lang":"go","doc":"Render (MsgPack) encodes the given interface object and writes data with custom ContentType.","code":"func (r MsgPack) Render(w http.ResponseWriter) error {\n\treturn WriteMsgPack(w, r.Data)\n}"} {"repo":"gin","file":"render/msgpack.go","line":39,"symbol":"WriteMsgPack","kind":"function","lang":"go","doc":"WriteMsgPack writes MsgPack ContentType and encodes the given interface object.","code":"func WriteMsgPack(w http.ResponseWriter, obj any) error {\n\twriteContentType(w, msgpackContentType)\n\tvar mh codec.MsgpackHandle\n\treturn codec.NewEncoder(w, &mh).Encode(obj)\n}"} {"repo":"gin","file":"render/msgpack.go","line":41,"symbol":"mh","kind":"variable","lang":"go","code":"mh codec.MsgpackHandle"} {"repo":"gin","file":"render/pdf.go","line":10,"symbol":"PDF","kind":"type","lang":"go","doc":"PDF contains the given PDF binary data.","code":"type PDF struct {\n\tData []byte\n}"} {"repo":"gin","file":"render/pdf.go","line":14,"symbol":"pdfContentType","kind":"variable","lang":"go","code":"pdfContentType = []string{\"application/pdf\"}"} {"repo":"gin","file":"render/pdf.go","line":17,"symbol":"Render","kind":"method","lang":"go","doc":"Render (PDF) writes PDF data with custom ContentType.","code":"func (r PDF) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\t_, err := w.Write(r.Data)\n\treturn err\n}"} {"repo":"gin","file":"render/pdf.go","line":24,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (PDF) writes PDF ContentType for response.","code":"func (r PDF) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, pdfContentType)\n}"} {"repo":"gin","file":"render/protobuf.go","line":14,"symbol":"ProtoBuf","kind":"type","lang":"go","doc":"ProtoBuf contains the given interface object.","code":"type ProtoBuf struct {\n\tData any\n}"} {"repo":"gin","file":"render/protobuf.go","line":18,"symbol":"protobufContentType","kind":"variable","lang":"go","code":"protobufContentType = []string{\"application/x-protobuf\"}"} {"repo":"gin","file":"render/protobuf.go","line":21,"symbol":"Render","kind":"method","lang":"go","doc":"Render (ProtoBuf) marshals the given interface object and writes data with custom ContentType.","code":"func (r ProtoBuf) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\n\tbytes, err := proto.Marshal(r.Data.(proto.Message))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(bytes)\n\treturn err\n}"} {"repo":"gin","file":"render/protobuf.go","line":34,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (ProtoBuf) writes ProtoBuf ContentType.","code":"func (r ProtoBuf) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, protobufContentType)\n}"} {"repo":"gin","file":"render/reader.go","line":14,"symbol":"Reader","kind":"type","lang":"go","doc":"Reader contains the IO reader and its length, and custom ContentType and other headers.","code":"type Reader struct {\n\tContentType string\n\tContentLength int64\n\tReader io.Reader\n\tHeaders map[string]string\n}"} {"repo":"gin","file":"render/reader.go","line":22,"symbol":"Render","kind":"method","lang":"go","doc":"Render (Reader) writes data with custom ContentType and headers.","code":"func (r Reader) Render(w http.ResponseWriter) (err error) {\n\tr.WriteContentType(w)\n\tif r.ContentLength >= 0 {\n\t\tif r.Headers == nil {\n\t\t\tr.Headers = map[string]string{}\n\t\t}\n\t\tr.Headers[\"Content-Length\"] = strconv.FormatInt(r.ContentLength, 10)\n\t}\n\tr.writeHeaders(w)\n\t_, err = io.Copy(w, r.Reader)\n\treturn\n}"} {"repo":"gin","file":"render/reader.go","line":36,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (Reader) writes custom ContentType.","code":"func (r Reader) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, []string{r.ContentType})\n}"} {"repo":"gin","file":"render/reader.go","line":41,"symbol":"writeHeaders","kind":"method","lang":"go","doc":"writeHeaders writes headers from r.Headers into response.","code":"func (r Reader) writeHeaders(w http.ResponseWriter) {\n\theader := w.Header()\n\tfor k, v := range r.Headers {\n\t\tif header.Get(k) == \"\" {\n\t\t\theader.Set(k, v)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"render/reader_test.go","line":15,"symbol":"TestReaderRenderNoHeaders","kind":"function","lang":"go","code":"func TestReaderRenderNoHeaders(t *testing.T) {\n\tcontent := \"test\"\n\tr := Reader{\n\t\tContentLength: int64(len(content)),\n\t\tReader: strings.NewReader(content),\n\t}\n\terr := r.Render(httptest.NewRecorder())\n\trequire.NoError(t, err)\n}"} {"repo":"gin","file":"render/redirect.go","line":13,"symbol":"Redirect","kind":"type","lang":"go","doc":"Redirect contains the http request reference and redirects status code and location.","code":"type Redirect struct {\n\tCode int\n\tRequest *http.Request\n\tLocation string\n}"} {"repo":"gin","file":"render/redirect.go","line":20,"symbol":"Render","kind":"method","lang":"go","doc":"Render (Redirect) redirects the http request to new location and writes redirect response.","code":"func (r Redirect) Render(w http.ResponseWriter) error {\n\tif (r.Code < http.StatusMultipleChoices || r.Code > http.StatusPermanentRedirect) && r.Code != http.StatusCreated {\n\t\tpanic(fmt.Sprintf(\"Cannot redirect with status code %d\", r.Code))\n\t}\n\thttp.Redirect(w, r.Request, r.Location, r.Code)\n\treturn nil\n}"} {"repo":"gin","file":"render/redirect.go","line":29,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (Redirect) don't write any ContentType.","code":"func (r Redirect) WriteContentType(http.ResponseWriter) {}"} {"repo":"gin","file":"render/render.go","line":10,"symbol":"Render","kind":"type","lang":"go","doc":"Render interface is to be implemented by JSON, XML, HTML, YAML and so on.","code":"type Render interface {\n\t// Render writes data with custom ContentType.\n\tRender(http.ResponseWriter) error\n\t// WriteContentType writes custom ContentType.\n\tWriteContentType(w http.ResponseWriter)\n}"} {"repo":"gin","file":"render/render.go","line":18,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*JSON)(nil)"} {"repo":"gin","file":"render/render.go","line":19,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*IndentedJSON)(nil)"} {"repo":"gin","file":"render/render.go","line":20,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*SecureJSON)(nil)"} {"repo":"gin","file":"render/render.go","line":21,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*JsonpJSON)(nil)"} {"repo":"gin","file":"render/render.go","line":22,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*XML)(nil)"} {"repo":"gin","file":"render/render.go","line":23,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*String)(nil)"} {"repo":"gin","file":"render/render.go","line":24,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*Redirect)(nil)"} {"repo":"gin","file":"render/render.go","line":25,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*Data)(nil)"} {"repo":"gin","file":"render/render.go","line":26,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*HTML)(nil)"} {"repo":"gin","file":"render/render.go","line":27,"symbol":"_","kind":"variable","lang":"go","code":"_ HTMLRender = (*HTMLDebug)(nil)"} {"repo":"gin","file":"render/render.go","line":28,"symbol":"_","kind":"variable","lang":"go","code":"_ HTMLRender = (*HTMLProduction)(nil)"} {"repo":"gin","file":"render/render.go","line":29,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*YAML)(nil)"} {"repo":"gin","file":"render/render.go","line":30,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*Reader)(nil)"} {"repo":"gin","file":"render/render.go","line":31,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*AsciiJSON)(nil)"} {"repo":"gin","file":"render/render.go","line":32,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*ProtoBuf)(nil)"} {"repo":"gin","file":"render/render.go","line":33,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*TOML)(nil)"} {"repo":"gin","file":"render/render.go","line":34,"symbol":"_","kind":"variable","lang":"go","code":"_ Render = (*PDF)(nil)"} {"repo":"gin","file":"render/render.go","line":37,"symbol":"writeContentType","kind":"function","lang":"go","code":"func writeContentType(w http.ResponseWriter, value []string) {\n\theader := w.Header()\n\tif val := header[\"Content-Type\"]; len(val) == 0 {\n\t\theader[\"Content-Type\"] = value\n\t}\n}"} {"repo":"gin","file":"render/render_msgpack_test.go","line":19,"symbol":"TestRenderMsgPack","kind":"function","lang":"go","code":"func TestRenderMsgPack(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := map[string]any{\n\t\t\"foo\": \"bar\",\n\t}\n\n\t(MsgPack{data}).WriteContentType(w)\n\tassert.Equal(t, \"application/msgpack; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\n\terr := (MsgPack{data}).Render(w)\n\n\trequire.NoError(t, err)\n\n\tvar decoded map[string]any\n\tvar mh codec.MsgpackHandle\n\tmh.RawToString = true\n\terr = codec.NewDecoderBytes(w.Body.Bytes(), &mh).Decode(&decoded)\n\trequire.NoError(t, err)\n\tassert.Equal(t, data, decoded)\n\tassert.Equal(t, \"application/msgpack; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_msgpack_test.go","line":32,"symbol":"decoded","kind":"variable","lang":"go","code":"decoded map[string]any"} {"repo":"gin","file":"render/render_msgpack_test.go","line":33,"symbol":"mh","kind":"variable","lang":"go","code":"mh codec.MsgpackHandle"} {"repo":"gin","file":"render/render_msgpack_test.go","line":41,"symbol":"TestWriteMsgPack","kind":"function","lang":"go","code":"func TestWriteMsgPack(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := map[string]any{\n\t\t\"foo\": \"bar\",\n\t\t\"num\": 42,\n\t}\n\n\terr := WriteMsgPack(w, data)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, \"application/msgpack; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\n\tvar decoded map[string]any\n\tvar mh codec.MsgpackHandle\n\tmh.RawToString = true\n\terr = codec.NewDecoderBytes(w.Body.Bytes(), &mh).Decode(&decoded)\n\trequire.NoError(t, err)\n\tassert.Len(t, decoded, 2)\n\tassert.Equal(t, \"bar\", decoded[\"foo\"])\n\tassert.EqualValues(t, 42, decoded[\"num\"])\n}"} {"repo":"gin","file":"render/render_msgpack_test.go","line":53,"symbol":"decoded","kind":"variable","lang":"go","code":"decoded map[string]any"} {"repo":"gin","file":"render/render_msgpack_test.go","line":54,"symbol":"mh","kind":"variable","lang":"go","code":"mh codec.MsgpackHandle"} {"repo":"gin","file":"render/render_msgpack_test.go","line":63,"symbol":"failWriter","kind":"type","lang":"go","code":"type failWriter struct {\n\t*httptest.ResponseRecorder\n}"} {"repo":"gin","file":"render/render_msgpack_test.go","line":67,"symbol":"Write","kind":"method","lang":"go","code":"func (w *failWriter) Write(data []byte) (int, error) {\n\treturn 0, errors.New(\"write error\")\n}"} {"repo":"gin","file":"render/render_msgpack_test.go","line":71,"symbol":"TestRenderMsgPackError","kind":"function","lang":"go","code":"func TestRenderMsgPackError(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := map[string]any{\n\t\t\"foo\": \"bar\",\n\t}\n\n\terr := (MsgPack{data}).Render(&failWriter{w})\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"write error\")\n}"} {"repo":"gin","file":"render/render_test.go","line":26,"symbol":"TestRenderJSON","kind":"function","lang":"go","code":"func TestRenderJSON(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := map[string]any{\n\t\t\"foo\": \"bar\",\n\t\t\"html\": \"\",\n\t}\n\n\t(JSON{data}).WriteContentType(w)\n\tassert.Equal(t, \"application/json; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\n\terr := (JSON{data}).Render(w)\n\n\trequire.NoError(t, err)\n\tassert.JSONEq(t, \"{\\\"foo\\\":\\\"bar\\\",\\\"html\\\":\\\"\\\\u003cb\\\\u003e\\\"}\", w.Body.String())\n\tassert.Equal(t, \"application/json; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":43,"symbol":"TestRenderJSONError","kind":"function","lang":"go","code":"func TestRenderJSONError(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := make(chan int)\n\n\t// json: unsupported type: chan int\n\trequire.Error(t, (JSON{data}).Render(w))\n}"} {"repo":"gin","file":"render/render_test.go","line":51,"symbol":"TestRenderIndentedJSON","kind":"function","lang":"go","code":"func TestRenderIndentedJSON(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := map[string]any{\n\t\t\"foo\": \"bar\",\n\t\t\"bar\": \"foo\",\n\t}\n\n\terr := (IndentedJSON{data}).Render(w)\n\n\trequire.NoError(t, err)\n\tassert.JSONEq(t, \"{\\n \\\"bar\\\": \\\"foo\\\",\\n \\\"foo\\\": \\\"bar\\\"\\n}\", w.Body.String())\n\tassert.Equal(t, \"application/json; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":65,"symbol":"TestRenderIndentedJSONPanics","kind":"function","lang":"go","code":"func TestRenderIndentedJSONPanics(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := make(chan int)\n\n\t// json: unsupported type: chan int\n\terr := (IndentedJSON{data}).Render(w)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"render/render_test.go","line":74,"symbol":"TestRenderSecureJSON","kind":"function","lang":"go","code":"func TestRenderSecureJSON(t *testing.T) {\n\tw1 := httptest.NewRecorder()\n\tdata := map[string]any{\n\t\t\"foo\": \"bar\",\n\t}\n\n\t(SecureJSON{\"while(1);\", data}).WriteContentType(w1)\n\tassert.Equal(t, \"application/json; charset=utf-8\", w1.Header().Get(\"Content-Type\"))\n\n\terr1 := (SecureJSON{\"while(1);\", data}).Render(w1)\n\n\trequire.NoError(t, err1)\n\tassert.JSONEq(t, \"{\\\"foo\\\":\\\"bar\\\"}\", w1.Body.String())\n\tassert.Equal(t, \"application/json; charset=utf-8\", w1.Header().Get(\"Content-Type\"))\n\n\tw2 := httptest.NewRecorder()\n\tdatas := []map[string]any{{\n\t\t\"foo\": \"bar\",\n\t}, {\n\t\t\"bar\": \"foo\",\n\t}}\n\n\terr2 := (SecureJSON{\"while(1);\", datas}).Render(w2)\n\trequire.NoError(t, err2)\n\tassert.Equal(t, \"while(1);[{\\\"foo\\\":\\\"bar\\\"},{\\\"bar\\\":\\\"foo\\\"}]\", w2.Body.String())\n\tassert.Equal(t, \"application/json; charset=utf-8\", w2.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":102,"symbol":"TestRenderSecureJSONFail","kind":"function","lang":"go","code":"func TestRenderSecureJSONFail(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := make(chan int)\n\n\t// json: unsupported type: chan int\n\terr := (SecureJSON{\"while(1);\", data}).Render(w)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"render/render_test.go","line":111,"symbol":"TestRenderJsonpJSON","kind":"function","lang":"go","code":"func TestRenderJsonpJSON(t *testing.T) {\n\tw1 := httptest.NewRecorder()\n\tdata := map[string]any{\n\t\t\"foo\": \"bar\",\n\t}\n\n\t(JsonpJSON{\"x\", data}).WriteContentType(w1)\n\tassert.Equal(t, \"application/javascript; charset=utf-8\", w1.Header().Get(\"Content-Type\"))\n\n\terr1 := (JsonpJSON{\"x\", data}).Render(w1)\n\n\trequire.NoError(t, err1)\n\tassert.Equal(t, \"x({\\\"foo\\\":\\\"bar\\\"});\", w1.Body.String())\n\tassert.Equal(t, \"application/javascript; charset=utf-8\", w1.Header().Get(\"Content-Type\"))\n\n\tw2 := httptest.NewRecorder()\n\tdatas := []map[string]any{{\n\t\t\"foo\": \"bar\",\n\t}, {\n\t\t\"bar\": \"foo\",\n\t}}\n\n\terr2 := (JsonpJSON{\"x\", datas}).Render(w2)\n\trequire.NoError(t, err2)\n\tassert.Equal(t, \"x([{\\\"foo\\\":\\\"bar\\\"},{\\\"bar\\\":\\\"foo\\\"}]);\", w2.Body.String())\n\tassert.Equal(t, \"application/javascript; charset=utf-8\", w2.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":139,"symbol":"errorWriter","kind":"type","lang":"go","code":"type errorWriter struct {\n\tbufString string\n\tErrThreshold int // 1-based threshold. If 1, errors on the 1st Write call.\n\twriteCount int\n\t*httptest.ResponseRecorder\n}"} {"repo":"gin","file":"render/render_test.go","line":146,"symbol":"_","kind":"variable","lang":"go","code":"_ http.ResponseWriter = (*errorWriter)(nil)"} {"repo":"gin","file":"render/render_test.go","line":148,"symbol":"Header","kind":"method","lang":"go","code":"func (w *errorWriter) Header() http.Header {\n\tif w.ResponseRecorder == nil {\n\t\tw.ResponseRecorder = httptest.NewRecorder()\n\t}\n\treturn w.ResponseRecorder.Header()\n}"} {"repo":"gin","file":"render/render_test.go","line":155,"symbol":"WriteHeader","kind":"method","lang":"go","code":"func (w *errorWriter) WriteHeader(statusCode int) {\n\tif w.ResponseRecorder == nil {\n\t\tw.ResponseRecorder = httptest.NewRecorder()\n\t}\n\tw.ResponseRecorder.WriteHeader(statusCode)\n}"} {"repo":"gin","file":"render/render_test.go","line":162,"symbol":"Write","kind":"method","lang":"go","code":"func (w *errorWriter) Write(buf []byte) (int, error) {\n\tw.writeCount++\n\tif (w.bufString != \"\" && string(buf) == w.bufString) || (w.ErrThreshold > 0 && w.writeCount >= w.ErrThreshold) {\n\t\treturn 0, errors.New(`write error`)\n\t}\n\tif w.ResponseRecorder == nil {\n\t\tw.ResponseRecorder = httptest.NewRecorder()\n\t}\n\treturn w.ResponseRecorder.Write(buf)\n}"} {"repo":"gin","file":"render/render_test.go","line":173,"symbol":"reset","kind":"method","lang":"go","code":"func (w *errorWriter) reset() {\n\tw.writeCount = 0\n\tw.ResponseRecorder = httptest.NewRecorder()\n}"} {"repo":"gin","file":"render/render_test.go","line":178,"symbol":"TestRenderJsonpJSONError","kind":"function","lang":"go","code":"func TestRenderJsonpJSONError(t *testing.T) {\n\tew := &errorWriter{\n\t\tResponseRecorder: httptest.NewRecorder(),\n\t}\n\n\tjsonpJSON := JsonpJSON{\n\t\tCallback: \"foo\",\n\t\tData: map[string]string{\n\t\t\t\"foo\": \"bar\",\n\t\t},\n\t}\n\n\t// error was returned while writing callback\n\tew.reset()\n\tew.ErrThreshold = 1\n\terr := jsonpJSON.Render(ew)\n\trequire.Error(t, err)\n\tassert.Equal(t, \"write error\", err.Error())\n\n\t// error was returned while writing \"(\"\n\tew.reset()\n\tew.ErrThreshold = 2\n\terr = jsonpJSON.Render(ew)\n\trequire.Error(t, err)\n\tassert.Equal(t, \"write error\", err.Error())\n\n\t// error was returned while writing data\n\tew.reset()\n\tew.ErrThreshold = 3\n\terr = jsonpJSON.Render(ew)\n\trequire.Error(t, err)\n\tassert.Equal(t, \"write error\", err.Error())\n\n\t// error was returned while writing \");\"\n\tew.reset()\n\tew.ErrThreshold = 4\n\terr = jsonpJSON.Render(ew)\n\trequire.Error(t, err)\n\tassert.Equal(t, \"write error\", err.Error())\n}"} {"repo":"gin","file":"render/render_test.go","line":219,"symbol":"TestRenderJsonpJSONError2","kind":"function","lang":"go","code":"func TestRenderJsonpJSONError2(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := map[string]any{\n\t\t\"foo\": \"bar\",\n\t}\n\t(JsonpJSON{\"\", data}).WriteContentType(w)\n\tassert.Equal(t, \"application/javascript; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\n\te := (JsonpJSON{\"\", data}).Render(w)\n\trequire.NoError(t, e)\n\n\tassert.JSONEq(t, \"{\\\"foo\\\":\\\"bar\\\"}\", w.Body.String())\n\tassert.Equal(t, \"application/javascript; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":234,"symbol":"TestRenderJsonpJSONFail","kind":"function","lang":"go","code":"func TestRenderJsonpJSONFail(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := make(chan int)\n\n\t// json: unsupported type: chan int\n\terr := (JsonpJSON{\"x\", data}).Render(w)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"render/render_test.go","line":243,"symbol":"TestRenderAsciiJSON","kind":"function","lang":"go","code":"func TestRenderAsciiJSON(t *testing.T) {\n\tw1 := httptest.NewRecorder()\n\tdata1 := map[string]any{\n\t\t\"lang\": \"GO语言\",\n\t\t\"tag\": \"
\",\n\t}\n\n\terr := (AsciiJSON{data1}).Render(w1)\n\n\trequire.NoError(t, err)\n\tassert.JSONEq(t, \"{\\\"lang\\\":\\\"GO\\\\u8bed\\\\u8a00\\\",\\\"tag\\\":\\\"\\\\u003cbr\\\\u003e\\\"}\", w1.Body.String())\n\tassert.Equal(t, \"application/json\", w1.Header().Get(\"Content-Type\"))\n\n\tw2 := httptest.NewRecorder()\n\tdata2 := 3.1415926\n\n\terr = (AsciiJSON{data2}).Render(w2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"3.1415926\", w2.Body.String())\n}"} {"repo":"gin","file":"render/render_test.go","line":264,"symbol":"TestRenderAsciiJSONFail","kind":"function","lang":"go","code":"func TestRenderAsciiJSONFail(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := make(chan int)\n\n\t// json: unsupported type: chan int\n\trequire.Error(t, (AsciiJSON{data}).Render(w))\n}"} {"repo":"gin","file":"render/render_test.go","line":272,"symbol":"TestRenderPureJSON","kind":"function","lang":"go","code":"func TestRenderPureJSON(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := map[string]any{\n\t\t\"foo\": \"bar\",\n\t\t\"html\": \"\",\n\t}\n\terr := (PureJSON{data}).Render(w)\n\trequire.NoError(t, err)\n\tassert.JSONEq(t, \"{\\\"foo\\\":\\\"bar\\\",\\\"html\\\":\\\"\\\"}\\n\", w.Body.String())\n\tassert.Equal(t, \"application/json; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":284,"symbol":"xmlmap","kind":"type","lang":"go","code":"type xmlmap map[string]any"} {"repo":"gin","file":"render/render_test.go","line":287,"symbol":"MarshalXML","kind":"method","lang":"go","doc":"MarshalXML allows xmlmap to be used with xml.Marshal.","code":"func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Name = xml.Name{\n\t\tSpace: \"\",\n\t\tLocal: \"map\",\n\t}\n\tif err := e.EncodeToken(start); err != nil {\n\t\treturn err\n\t}\n\tfor key, value := range h {\n\t\telem := xml.StartElement{\n\t\t\tName: xml.Name{Space: \"\", Local: key},\n\t\t\tAttr: []xml.Attr{},\n\t\t}\n\t\tif err := e.EncodeElement(value, elem); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn e.EncodeToken(xml.EndElement{Name: start.Name})\n}"} {"repo":"gin","file":"render/render_test.go","line":308,"symbol":"TestRenderYAML","kind":"function","lang":"go","code":"func TestRenderYAML(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := `\na : Easy!\nb:\n\tc: 2\n\td: [3, 4]\n\t`\n\t(YAML{data}).WriteContentType(w)\n\tassert.Equal(t, \"application/yaml; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\n\terr := (YAML{data}).Render(w)\n\trequire.NoError(t, err)\n\n\t// With github.com/goccy/go-yaml, the output format is different from gopkg.in/yaml.v3\n\t// We're checking that the output contains the expected data, not the exact formatting\n\toutput := w.Body.String()\n\tassert.Contains(t, output, \"a : Easy!\")\n\tassert.Contains(t, output, \"b:\")\n\tassert.Contains(t, output, \"c: 2\")\n\tassert.Contains(t, output, \"d: [3, 4]\")\n\tassert.Equal(t, \"application/yaml; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":332,"symbol":"fail","kind":"type","lang":"go","code":"type fail struct{}"} {"repo":"gin","file":"render/render_test.go","line":335,"symbol":"MarshalYAML","kind":"method","lang":"go","doc":"MarshalYAML returns an error for YAML rendering failure tests.","code":"func (ft *fail) MarshalYAML() (any, error) {\n\treturn nil, errors.New(\"fail\")\n}"} {"repo":"gin","file":"render/render_test.go","line":339,"symbol":"TestRenderYAMLFail","kind":"function","lang":"go","code":"func TestRenderYAMLFail(t *testing.T) {\n\tw := httptest.NewRecorder()\n\terr := (YAML{&fail{}}).Render(w)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"render/render_test.go","line":345,"symbol":"TestRenderTOML","kind":"function","lang":"go","code":"func TestRenderTOML(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := map[string]any{\n\t\t\"foo\": \"bar\",\n\t\t\"html\": \"\",\n\t}\n\t(TOML{data}).WriteContentType(w)\n\tassert.Equal(t, \"application/toml; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\n\terr := (TOML{data}).Render(w)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"foo = 'bar'\\nhtml = ''\\n\", w.Body.String())\n\tassert.Equal(t, \"application/toml; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":360,"symbol":"TestRenderTOMLFail","kind":"function","lang":"go","code":"func TestRenderTOMLFail(t *testing.T) {\n\tw := httptest.NewRecorder()\n\terr := (TOML{net.IPv4bcast}).Render(w)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"render/render_test.go","line":367,"symbol":"TestRenderProtoBuf","kind":"function","lang":"go","doc":"test Protobuf rendering","code":"func TestRenderProtoBuf(t *testing.T) {\n\tw := httptest.NewRecorder()\n\treps := []int64{int64(1), int64(2)}\n\tlabel := \"test\"\n\tdata := &testdata.Test{\n\t\tLabel: &label,\n\t\tReps: reps,\n\t}\n\n\t(ProtoBuf{data}).WriteContentType(w)\n\tprotoData, err := proto.Marshal(data)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"application/x-protobuf\", w.Header().Get(\"Content-Type\"))\n\n\terr = (ProtoBuf{data}).Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, string(protoData), w.Body.String())\n\tassert.Equal(t, \"application/x-protobuf\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":388,"symbol":"TestRenderProtoBufFail","kind":"function","lang":"go","code":"func TestRenderProtoBufFail(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := &testdata.Test{}\n\terr := (ProtoBuf{data}).Render(w)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"render/render_test.go","line":395,"symbol":"TestRenderBSON","kind":"function","lang":"go","code":"func TestRenderBSON(t *testing.T) {\n\tw := httptest.NewRecorder()\n\treps := []int64{int64(1), int64(2)}\n\ttype mystruct struct {\n\t\tLabel string\n\t\tReps []int64\n\t}\n\n\tdata := &mystruct{\n\t\tLabel: \"test\",\n\t\tReps: reps,\n\t}\n\n\t(BSON{data}).WriteContentType(w)\n\tbsonData, err := bson.Marshal(data)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"application/bson\", w.Header().Get(\"Content-Type\"))\n\n\terr = (BSON{data}).Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, bsonData, w.Body.Bytes())\n\tassert.Equal(t, \"application/bson\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":398,"symbol":"mystruct","kind":"type","lang":"go","code":"type mystruct struct {\n\t\tLabel string\n\t\tReps []int64\n\t}"} {"repo":"gin","file":"render/render_test.go","line":420,"symbol":"TestRenderBSONError","kind":"function","lang":"go","code":"func TestRenderBSONError(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := make(chan int)\n\n\terr := (BSON{data}).Render(w)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"render/render_test.go","line":428,"symbol":"TestRenderBSONWriteError","kind":"function","lang":"go","code":"func TestRenderBSONWriteError(t *testing.T) {\n\ttype testStruct struct {\n\t\tValue string\n\t}\n\tdata := &testStruct{Value: \"test\"}\n\n\tew := &errorWriter{\n\t\tErrThreshold: 1,\n\t\tResponseRecorder: httptest.NewRecorder(),\n\t}\n\n\terr := (BSON{data}).Render(ew)\n\trequire.Error(t, err)\n\tassert.Equal(t, \"write error\", err.Error())\n}"} {"repo":"gin","file":"render/render_test.go","line":429,"symbol":"testStruct","kind":"type","lang":"go","code":"type testStruct struct {\n\t\tValue string\n\t}"} {"repo":"gin","file":"render/render_test.go","line":444,"symbol":"TestRenderXML","kind":"function","lang":"go","code":"func TestRenderXML(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := xmlmap{\n\t\t\"foo\": \"bar\",\n\t}\n\n\t(XML{data}).WriteContentType(w)\n\tassert.Equal(t, \"application/xml; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\n\terr := (XML{data}).Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"bar\", w.Body.String())\n\tassert.Equal(t, \"application/xml; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":460,"symbol":"TestRenderXMLError","kind":"function","lang":"go","code":"func TestRenderXMLError(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := make(chan int)\n\n\terr := (XML{data}).Render(w)\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"xml: unsupported type: chan int\")\n}"} {"repo":"gin","file":"render/render_test.go","line":469,"symbol":"TestRenderPDF","kind":"function","lang":"go","code":"func TestRenderPDF(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := []byte(\"%Test pdf content\")\n\n\tpdf := PDF{data}\n\n\tpdf.WriteContentType(w)\n\tassert.Equal(t, \"application/pdf\", w.Header().Get(\"Content-Type\"))\n\n\terr := pdf.Render(w)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, data, w.Body.Bytes())\n\tassert.Equal(t, \"application/pdf\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":485,"symbol":"TestRenderRedirect","kind":"function","lang":"go","code":"func TestRenderRedirect(t *testing.T) {\n\treq, err := http.NewRequest(http.MethodGet, \"/test-redirect\", nil)\n\trequire.NoError(t, err)\n\n\tdata1 := Redirect{\n\t\tCode: http.StatusMovedPermanently,\n\t\tRequest: req,\n\t\tLocation: \"/new/location\",\n\t}\n\n\tw := httptest.NewRecorder()\n\terr = data1.Render(w)\n\trequire.NoError(t, err)\n\n\tdata2 := Redirect{\n\t\tCode: http.StatusOK,\n\t\tRequest: req,\n\t\tLocation: \"/new/location\",\n\t}\n\n\tw = httptest.NewRecorder()\n\tassert.PanicsWithValue(t, \"Cannot redirect with status code 200\", func() {\n\t\terr := data2.Render(w)\n\t\trequire.NoError(t, err)\n\t})\n\n\tdata3 := Redirect{\n\t\tCode: http.StatusCreated,\n\t\tRequest: req,\n\t\tLocation: \"/new/location\",\n\t}\n\n\tw = httptest.NewRecorder()\n\terr = data3.Render(w)\n\trequire.NoError(t, err)\n\n\t// only improve coverage\n\tdata2.WriteContentType(w)\n}"} {"repo":"gin","file":"render/render_test.go","line":525,"symbol":"TestRenderData","kind":"function","lang":"go","code":"func TestRenderData(t *testing.T) {\n\tw := httptest.NewRecorder()\n\tdata := []byte(\"#!PNG some raw data\")\n\n\terr := (Data{\n\t\tContentType: \"image/png\",\n\t\tData: data,\n\t}).Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"#!PNG some raw data\", w.Body.String())\n\tassert.Equal(t, \"image/png\", w.Header().Get(\"Content-Type\"))\n\tassert.Equal(t, \"19\", w.Header().Get(\"Content-Length\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":540,"symbol":"TestRenderDataContentLength","kind":"function","lang":"go","code":"func TestRenderDataContentLength(t *testing.T) {\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tsize, err := strconv.Atoi(r.URL.Query().Get(\"size\"))\n\t\tassert.NoError(t, err)\n\n\t\tdata := Data{\n\t\t\tContentType: \"application/octet-stream\",\n\t\t\tData: make([]byte, size),\n\t\t}\n\t\tassert.NoError(t, data.Render(w))\n\t}))\n\tt.Cleanup(srv.Close)\n\n\tfor _, size := range []int{0, 1, 100, 100_000} {\n\t\tt.Run(strconv.Itoa(size), func(t *testing.T) {\n\t\t\tresp, err := http.Get(srv.URL + \"?size=\" + strconv.Itoa(size))\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer resp.Body.Close()\n\n\t\t\tassert.Equal(t, \"application/octet-stream\", resp.Header.Get(\"Content-Type\"))\n\t\t\tassert.Equal(t, strconv.Itoa(size), resp.Header.Get(\"Content-Length\"))\n\n\t\t\tactual, err := io.Copy(io.Discard, resp.Body)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.EqualValues(t, size, actual)\n\t\t})\n\t}\n}"} {"repo":"gin","file":"render/render_test.go","line":569,"symbol":"TestRenderDataError","kind":"function","lang":"go","code":"func TestRenderDataError(t *testing.T) {\n\tew := &errorWriter{\n\t\tErrThreshold: 1,\n\t\tResponseRecorder: httptest.NewRecorder(),\n\t}\n\tdata := []byte(\"#!PNG some raw data\")\n\n\terr := (Data{\n\t\tContentType: \"image/png\",\n\t\tData: data,\n\t}).Render(ew)\n\n\trequire.Error(t, err)\n\tassert.Equal(t, \"write error\", err.Error())\n}"} {"repo":"gin","file":"render/render_test.go","line":585,"symbol":"TestRenderString","kind":"function","lang":"go","code":"func TestRenderString(t *testing.T) {\n\tw := httptest.NewRecorder()\n\n\t(String{\n\t\tFormat: \"hello %s %d\",\n\t\tData: []any{},\n\t}).WriteContentType(w)\n\tassert.Equal(t, \"text/plain; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\n\terr := (String{\n\t\tFormat: \"hola %s %d\",\n\t\tData: []any{\"manu\", 2},\n\t}).Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"hola manu 2\", w.Body.String())\n\tassert.Equal(t, \"text/plain; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":604,"symbol":"TestRenderStringLenZero","kind":"function","lang":"go","code":"func TestRenderStringLenZero(t *testing.T) {\n\tw := httptest.NewRecorder()\n\n\terr := (String{\n\t\tFormat: \"hola %s %d\",\n\t\tData: []any{},\n\t}).Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"hola %s %d\", w.Body.String())\n\tassert.Equal(t, \"text/plain; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":617,"symbol":"TestRenderHTMLTemplate","kind":"function","lang":"go","code":"func TestRenderHTMLTemplate(t *testing.T) {\n\tw := httptest.NewRecorder()\n\ttempl := template.Must(template.New(\"t\").Parse(`Hello {{.name}}`))\n\n\thtmlRender := HTMLProduction{Template: templ}\n\tinstance := htmlRender.Instance(\"t\", map[string]any{\n\t\t\"name\": \"alexandernyquist\",\n\t})\n\n\terr := instance.Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"Hello alexandernyquist\", w.Body.String())\n\tassert.Equal(t, \"text/html; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":633,"symbol":"TestRenderHTMLWithoutTemplate","kind":"function","lang":"go","code":"func TestRenderHTMLWithoutTemplate(t *testing.T) {\n\tw := httptest.NewRecorder()\n\n\terr := (HTML{}).Render(w)\n\n\trequire.EqualError(t, err, \"html renderer is not configured\")\n\tassert.Empty(t, w.Body.String())\n\tassert.Equal(t, \"text/html; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":643,"symbol":"TestRenderHTMLTemplateEmptyName","kind":"function","lang":"go","code":"func TestRenderHTMLTemplateEmptyName(t *testing.T) {\n\tw := httptest.NewRecorder()\n\ttempl := template.Must(template.New(\"\").Parse(`Hello {{.name}}`))\n\n\thtmlRender := HTMLProduction{Template: templ}\n\tinstance := htmlRender.Instance(\"\", map[string]any{\n\t\t\"name\": \"alexandernyquist\",\n\t})\n\n\terr := instance.Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"Hello alexandernyquist\", w.Body.String())\n\tassert.Equal(t, \"text/html; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":659,"symbol":"TestRenderHTMLDebugFiles","kind":"function","lang":"go","code":"func TestRenderHTMLDebugFiles(t *testing.T) {\n\tw := httptest.NewRecorder()\n\thtmlRender := HTMLDebug{\n\t\tFiles: []string{\"../testdata/template/hello.tmpl\"},\n\t\tGlob: \"\",\n\t\tFileSystem: nil,\n\t\tPatterns: nil,\n\t\tDelims: Delims{Left: \"{[{\", Right: \"}]}\"},\n\t\tFuncMap: nil,\n\t}\n\tinstance := htmlRender.Instance(\"hello.tmpl\", map[string]any{\n\t\t\"name\": \"thinkerou\",\n\t})\n\n\terr := instance.Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"

Hello thinkerou

\", w.Body.String())\n\tassert.Equal(t, \"text/html; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":680,"symbol":"TestRenderHTMLDebugGlob","kind":"function","lang":"go","code":"func TestRenderHTMLDebugGlob(t *testing.T) {\n\tw := httptest.NewRecorder()\n\thtmlRender := HTMLDebug{\n\t\tFiles: nil,\n\t\tGlob: \"../testdata/template/hello*\",\n\t\tFileSystem: nil,\n\t\tPatterns: nil,\n\t\tDelims: Delims{Left: \"{[{\", Right: \"}]}\"},\n\t\tFuncMap: nil,\n\t}\n\tinstance := htmlRender.Instance(\"hello.tmpl\", map[string]any{\n\t\t\"name\": \"thinkerou\",\n\t})\n\n\terr := instance.Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"

Hello thinkerou

\", w.Body.String())\n\tassert.Equal(t, \"text/html; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":701,"symbol":"TestRenderHTMLDebugFS","kind":"function","lang":"go","code":"func TestRenderHTMLDebugFS(t *testing.T) {\n\tw := httptest.NewRecorder()\n\thtmlRender := HTMLDebug{\n\t\tFiles: nil,\n\t\tGlob: \"\",\n\t\tFileSystem: http.Dir(\"../testdata/template\"),\n\t\tPatterns: []string{\"hello.tmpl\"},\n\t\tDelims: Delims{Left: \"{[{\", Right: \"}]}\"},\n\t\tFuncMap: nil,\n\t}\n\tinstance := htmlRender.Instance(\"hello.tmpl\", map[string]any{\n\t\t\"name\": \"thinkerou\",\n\t})\n\n\terr := instance.Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"

Hello thinkerou

\", w.Body.String())\n\tassert.Equal(t, \"text/html; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":722,"symbol":"TestRenderHTMLDebugPanics","kind":"function","lang":"go","code":"func TestRenderHTMLDebugPanics(t *testing.T) {\n\thtmlRender := HTMLDebug{\n\t\tFiles: nil,\n\t\tGlob: \"\",\n\t\tFileSystem: nil,\n\t\tPatterns: nil,\n\t\tDelims: Delims{\"{{\", \"}}\"},\n\t\tFuncMap: nil,\n\t}\n\tassert.Panics(t, func() { htmlRender.Instance(\"\", nil) })\n}"} {"repo":"gin","file":"render/render_test.go","line":734,"symbol":"TestRenderHTMLTemplateError","kind":"function","lang":"go","code":"func TestRenderHTMLTemplateError(t *testing.T) {\n\tw := httptest.NewRecorder()\n\ttempl := template.Must(template.New(\"t\").Parse(`Hello {{if .name}}{{.name.DoesNotExist}}{{end}}`))\n\n\thtmlRender := HTMLProduction{Template: templ}\n\tinstance := htmlRender.Instance(\"t\", map[string]any{\n\t\t\"name\": \"alexandernyquist\",\n\t})\n\n\terr := instance.Render(w)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"render/render_test.go","line":747,"symbol":"TestRenderHTMLTemplateExecuteError","kind":"function","lang":"go","code":"func TestRenderHTMLTemplateExecuteError(t *testing.T) {\n\tw := httptest.NewRecorder()\n\ttempl := template.Must(template.New(\"t\").Parse(`Hello {{.name.invalid}}`))\n\n\thtmlRender := HTMLProduction{Template: templ}\n\tinstance := htmlRender.Instance(\"t\", map[string]any{\n\t\t\"name\": \"alexandernyquist\",\n\t})\n\n\terr := instance.Render(w)\n\trequire.Error(t, err)\n}"} {"repo":"gin","file":"render/render_test.go","line":760,"symbol":"TestRenderReader","kind":"function","lang":"go","code":"func TestRenderReader(t *testing.T) {\n\tw := httptest.NewRecorder()\n\n\tbody := \"#!PNG some raw data\"\n\theaders := make(map[string]string)\n\theaders[\"Content-Disposition\"] = `attachment; filename=\"filename.png\"`\n\theaders[\"x-request-id\"] = \"requestId\"\n\n\terr := (Reader{\n\t\tContentLength: int64(len(body)),\n\t\tContentType: \"image/png\",\n\t\tReader: strings.NewReader(body),\n\t\tHeaders: headers,\n\t}).Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, body, w.Body.String())\n\tassert.Equal(t, \"image/png\", w.Header().Get(\"Content-Type\"))\n\tassert.Equal(t, strconv.Itoa(len(body)), w.Header().Get(\"Content-Length\"))\n\tassert.Equal(t, headers[\"Content-Disposition\"], w.Header().Get(\"Content-Disposition\"))\n\tassert.Equal(t, headers[\"x-request-id\"], w.Header().Get(\"x-request-id\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":783,"symbol":"TestRenderReaderNoContentLength","kind":"function","lang":"go","code":"func TestRenderReaderNoContentLength(t *testing.T) {\n\tw := httptest.NewRecorder()\n\n\tbody := \"#!PNG some raw data\"\n\theaders := make(map[string]string)\n\theaders[\"Content-Disposition\"] = `attachment; filename=\"filename.png\"`\n\theaders[\"x-request-id\"] = \"requestId\"\n\n\terr := (Reader{\n\t\tContentLength: -1,\n\t\tContentType: \"image/png\",\n\t\tReader: strings.NewReader(body),\n\t\tHeaders: headers,\n\t}).Render(w)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, body, w.Body.String())\n\tassert.Equal(t, \"image/png\", w.Header().Get(\"Content-Type\"))\n\tassert.NotContains(t, \"Content-Length\", w.Header())\n\tassert.Equal(t, headers[\"Content-Disposition\"], w.Header().Get(\"Content-Disposition\"))\n\tassert.Equal(t, headers[\"x-request-id\"], w.Header().Get(\"x-request-id\"))\n}"} {"repo":"gin","file":"render/render_test.go","line":806,"symbol":"TestRenderWriteError","kind":"function","lang":"go","code":"func TestRenderWriteError(t *testing.T) {\n\tdata := []any{\"value1\", \"value2\"}\n\tprefix := \"my-prefix:\"\n\tr := SecureJSON{Data: data, Prefix: prefix}\n\tew := &errorWriter{\n\t\tErrThreshold: 1,\n\t\tResponseRecorder: httptest.NewRecorder(),\n\t}\n\terr := r.Render(ew)\n\trequire.Error(t, err)\n\tassert.Equal(t, \"write error\", err.Error())\n}"} {"repo":"gin","file":"render/text.go","line":15,"symbol":"String","kind":"type","lang":"go","doc":"String contains the given interface object slice and its format.","code":"type String struct {\n\tFormat string\n\tData []any\n}"} {"repo":"gin","file":"render/text.go","line":20,"symbol":"plainContentType","kind":"variable","lang":"go","code":"plainContentType = []string{\"text/plain; charset=utf-8\"}"} {"repo":"gin","file":"render/text.go","line":23,"symbol":"Render","kind":"method","lang":"go","doc":"Render (String) writes data with custom ContentType.","code":"func (r String) Render(w http.ResponseWriter) error {\n\treturn WriteString(w, r.Format, r.Data)\n}"} {"repo":"gin","file":"render/text.go","line":28,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (String) writes Plain ContentType.","code":"func (r String) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, plainContentType)\n}"} {"repo":"gin","file":"render/text.go","line":33,"symbol":"WriteString","kind":"function","lang":"go","doc":"WriteString writes data according to its format and write custom ContentType.","code":"func WriteString(w http.ResponseWriter, format string, data []any) (err error) {\n\twriteContentType(w, plainContentType)\n\tif len(data) > 0 {\n\t\t_, err = fmt.Fprintf(w, format, data...)\n\t\treturn\n\t}\n\t_, err = w.Write(bytesconv.StringToBytes(format))\n\treturn\n}"} {"repo":"gin","file":"render/toml.go","line":14,"symbol":"TOML","kind":"type","lang":"go","doc":"TOML contains the given interface object.","code":"type TOML struct {\n\tData any\n}"} {"repo":"gin","file":"render/toml.go","line":18,"symbol":"tomlContentType","kind":"variable","lang":"go","code":"tomlContentType = []string{\"application/toml; charset=utf-8\"}"} {"repo":"gin","file":"render/toml.go","line":21,"symbol":"Render","kind":"method","lang":"go","doc":"Render (TOML) marshals the given interface object and writes data with custom ContentType.","code":"func (r TOML) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\n\tbytes, err := toml.Marshal(r.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(bytes)\n\treturn err\n}"} {"repo":"gin","file":"render/toml.go","line":34,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (TOML) writes TOML ContentType for response.","code":"func (r TOML) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, tomlContentType)\n}"} {"repo":"gin","file":"render/xml.go","line":13,"symbol":"XML","kind":"type","lang":"go","doc":"XML contains the given interface object.","code":"type XML struct {\n\tData any\n}"} {"repo":"gin","file":"render/xml.go","line":17,"symbol":"xmlContentType","kind":"variable","lang":"go","code":"xmlContentType = []string{\"application/xml; charset=utf-8\"}"} {"repo":"gin","file":"render/xml.go","line":20,"symbol":"Render","kind":"method","lang":"go","doc":"Render (XML) encodes the given interface object and writes data with custom ContentType.","code":"func (r XML) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\treturn xml.NewEncoder(w).Encode(r.Data)\n}"} {"repo":"gin","file":"render/xml.go","line":26,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (XML) writes XML ContentType for response.","code":"func (r XML) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, xmlContentType)\n}"} {"repo":"gin","file":"render/yaml.go","line":14,"symbol":"YAML","kind":"type","lang":"go","doc":"YAML contains the given interface object.","code":"type YAML struct {\n\tData any\n}"} {"repo":"gin","file":"render/yaml.go","line":18,"symbol":"yamlContentType","kind":"variable","lang":"go","code":"yamlContentType = []string{\"application/yaml; charset=utf-8\"}"} {"repo":"gin","file":"render/yaml.go","line":21,"symbol":"Render","kind":"method","lang":"go","doc":"Render (YAML) marshals the given interface object and writes data with custom ContentType.","code":"func (r YAML) Render(w http.ResponseWriter) error {\n\tr.WriteContentType(w)\n\n\tbytes, err := yaml.Marshal(r.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(bytes)\n\treturn err\n}"} {"repo":"gin","file":"render/yaml.go","line":34,"symbol":"WriteContentType","kind":"method","lang":"go","doc":"WriteContentType (YAML) writes YAML ContentType for response.","code":"func (r YAML) WriteContentType(w http.ResponseWriter) {\n\twriteContentType(w, yamlContentType)\n}"} {"repo":"gin","file":"response_writer.go","line":16,"symbol":"noWritten","kind":"constant","lang":"go","code":"noWritten = -1"} {"repo":"gin","file":"response_writer.go","line":17,"symbol":"defaultStatus","kind":"constant","lang":"go","code":"defaultStatus = http.StatusOK"} {"repo":"gin","file":"response_writer.go","line":20,"symbol":"errHijackAlreadyWritten","kind":"variable","lang":"go","code":"errHijackAlreadyWritten = errors.New(\"gin: response body already written\")"} {"repo":"gin","file":"response_writer.go","line":23,"symbol":"ResponseWriter","kind":"type","lang":"go","doc":"ResponseWriter ...","code":"type ResponseWriter interface {\n\thttp.ResponseWriter\n\thttp.Hijacker\n\thttp.Flusher\n\thttp.CloseNotifier\n\n\t// Status returns the HTTP response status code of the current request.\n\tStatus() int\n\n\t// Size returns the number of bytes already written into the response http body.\n\t// See Written()\n\tSize() int\n\n\t// WriteString writes the string into the response body.\n\tWriteString(string) (int, error)\n\n\t// Written returns true if the response body was already written.\n\tWritten() bool\n\n\t// WriteHeaderNow forces to write the http header (status code + headers).\n\tWriteHeaderNow()\n\n\t// Pusher get the http.Pusher for server push\n\tPusher() http.Pusher\n}"} {"repo":"gin","file":"response_writer.go","line":49,"symbol":"responseWriter","kind":"type","lang":"go","code":"type responseWriter struct {\n\thttp.ResponseWriter\n\tsize int\n\tstatus int\n}"} {"repo":"gin","file":"response_writer.go","line":55,"symbol":"_","kind":"variable","lang":"go","code":"_ ResponseWriter = (*responseWriter)(nil)"} {"repo":"gin","file":"response_writer.go","line":57,"symbol":"Unwrap","kind":"method","lang":"go","code":"func (w *responseWriter) Unwrap() http.ResponseWriter {\n\treturn w.ResponseWriter\n}"} {"repo":"gin","file":"response_writer.go","line":61,"symbol":"reset","kind":"method","lang":"go","code":"func (w *responseWriter) reset(writer http.ResponseWriter) {\n\tw.ResponseWriter = writer\n\tw.size = noWritten\n\tw.status = defaultStatus\n}"} {"repo":"gin","file":"response_writer.go","line":67,"symbol":"WriteHeader","kind":"method","lang":"go","code":"func (w *responseWriter) WriteHeader(code int) {\n\tif code > 0 && w.status != code {\n\t\tif w.Written() {\n\t\t\tdebugPrint(\"[WARNING] Headers were already written. Wanted to override status code %d with %d\", w.status, code)\n\t\t\treturn\n\t\t}\n\t\tw.status = code\n\t}\n}"} {"repo":"gin","file":"response_writer.go","line":77,"symbol":"WriteHeaderNow","kind":"method","lang":"go","code":"func (w *responseWriter) WriteHeaderNow() {\n\tif !w.Written() {\n\t\tw.size = 0\n\t\tw.ResponseWriter.WriteHeader(w.status)\n\t}\n}"} {"repo":"gin","file":"response_writer.go","line":84,"symbol":"Write","kind":"method","lang":"go","code":"func (w *responseWriter) Write(data []byte) (n int, err error) {\n\tw.WriteHeaderNow()\n\tn, err = w.ResponseWriter.Write(data)\n\tw.size += n\n\treturn\n}"} {"repo":"gin","file":"response_writer.go","line":91,"symbol":"WriteString","kind":"method","lang":"go","code":"func (w *responseWriter) WriteString(s string) (n int, err error) {\n\tw.WriteHeaderNow()\n\tn, err = io.WriteString(w.ResponseWriter, s)\n\tw.size += n\n\treturn\n}"} {"repo":"gin","file":"response_writer.go","line":98,"symbol":"Status","kind":"method","lang":"go","code":"func (w *responseWriter) Status() int {\n\treturn w.status\n}"} {"repo":"gin","file":"response_writer.go","line":102,"symbol":"Size","kind":"method","lang":"go","code":"func (w *responseWriter) Size() int {\n\treturn w.size\n}"} {"repo":"gin","file":"response_writer.go","line":106,"symbol":"Written","kind":"method","lang":"go","code":"func (w *responseWriter) Written() bool {\n\treturn w.size != noWritten\n}"} {"repo":"gin","file":"response_writer.go","line":111,"symbol":"Hijack","kind":"method","lang":"go","doc":"Hijack implements the http.Hijacker interface.","code":"func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\t// Allow hijacking before any data is written (size == -1) or after headers are written (size == 0),\n\t// but not after body data is written (size > 0). For compatibility with websocket libraries (e.g., github.com/coder/websocket)\n\tif w.size > 0 {\n\t\treturn nil, nil, errHijackAlreadyWritten\n\t}\n\thijacker, ok := w.ResponseWriter.(http.Hijacker)\n\tif !ok {\n\t\treturn nil, nil, http.ErrNotSupported\n\t}\n\tif w.size < 0 {\n\t\tw.size = 0\n\t}\n\treturn hijacker.Hijack()\n}"} {"repo":"gin","file":"response_writer.go","line":128,"symbol":"CloseNotify","kind":"method","lang":"go","doc":"CloseNotify implements the http.CloseNotifier interface.","code":"func (w *responseWriter) CloseNotify() <-chan bool {\n\tif cn, ok := w.ResponseWriter.(http.CloseNotifier); ok {\n\t\treturn cn.CloseNotify()\n\t}\n\treturn nil\n}"} {"repo":"gin","file":"response_writer.go","line":136,"symbol":"Flush","kind":"method","lang":"go","doc":"Flush implements the http.Flusher interface.","code":"func (w *responseWriter) Flush() {\n\tw.WriteHeaderNow()\n\tif f, ok := w.ResponseWriter.(http.Flusher); ok {\n\t\tf.Flush()\n\t}\n}"} {"repo":"gin","file":"response_writer.go","line":143,"symbol":"Pusher","kind":"method","lang":"go","code":"func (w *responseWriter) Pusher() (pusher http.Pusher) {\n\tif pusher, ok := w.ResponseWriter.(http.Pusher); ok {\n\t\treturn pusher\n\t}\n\treturn nil\n}"} {"repo":"gin","file":"response_writer_test.go","line":19,"symbol":"TestResponseWriterFlushWithFlusher","kind":"function","lang":"go","doc":"TestResponseWriterFlushWithFlusher verifies Flush() calls the underlying Flusher.","code":"func TestResponseWriterFlushWithFlusher(t *testing.T) {\n\ttestWriter := httptest.NewRecorder()\n\twriter := &responseWriter{ResponseWriter: testWriter}\n\twriter.Flush()\n\tassert.True(t, testWriter.Flushed)\n}"} {"repo":"gin","file":"response_writer_test.go","line":29,"symbol":"TestResponseWriterFlushWithNonFlusher","kind":"function","lang":"go","doc":"TestResponseWriterFlushWithNonFlusher verifies Flush() is a no-op when the underlying ResponseWriter does not implement http.Flusher. Guards against the panic reported in https://github.com/gin-gonic/gin/issues/4460","code":"func TestResponseWriterFlushWithNonFlusher(t *testing.T) {\n\tnonFlusher := &nonFlusherWriter{header: http.Header{}}\n\twriter := &responseWriter{ResponseWriter: nonFlusher}\n\trequire.NotPanics(t, func() {\n\t\twriter.Flush()\n\t})\n}"} {"repo":"gin","file":"response_writer_test.go","line":38,"symbol":"nonFlusherWriter","kind":"type","lang":"go","doc":"nonFlusherWriter is a minimal http.ResponseWriter that does NOT implement http.Flusher.","code":"type nonFlusherWriter struct {\n\theader http.Header\n}"} {"repo":"gin","file":"response_writer_test.go","line":42,"symbol":"Header","kind":"method","lang":"go","code":"func (w *nonFlusherWriter) Header() http.Header { return w.header }"} {"repo":"gin","file":"response_writer_test.go","line":43,"symbol":"Write","kind":"method","lang":"go","code":"func (w *nonFlusherWriter) Write(b []byte) (int, error) { return len(b), nil }"} {"repo":"gin","file":"response_writer_test.go","line":44,"symbol":"WriteHeader","kind":"method","lang":"go","code":"func (w *nonFlusherWriter) WriteHeader(code int) {}"} {"repo":"gin","file":"response_writer_test.go","line":47,"symbol":"_","kind":"variable","lang":"go","code":"_ ResponseWriter = &responseWriter{}"} {"repo":"gin","file":"response_writer_test.go","line":48,"symbol":"_","kind":"variable","lang":"go","code":"_ http.ResponseWriter = &responseWriter{}"} {"repo":"gin","file":"response_writer_test.go","line":49,"symbol":"_","kind":"variable","lang":"go","code":"_ http.ResponseWriter = ResponseWriter(&responseWriter{})"} {"repo":"gin","file":"response_writer_test.go","line":50,"symbol":"_","kind":"variable","lang":"go","code":"_ http.Hijacker = ResponseWriter(&responseWriter{})"} {"repo":"gin","file":"response_writer_test.go","line":51,"symbol":"_","kind":"variable","lang":"go","code":"_ http.Flusher = ResponseWriter(&responseWriter{})"} {"repo":"gin","file":"response_writer_test.go","line":52,"symbol":"_","kind":"variable","lang":"go","code":"_ http.CloseNotifier = ResponseWriter(&responseWriter{})"} {"repo":"gin","file":"response_writer_test.go","line":55,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tSetMode(TestMode)\n}"} {"repo":"gin","file":"response_writer_test.go","line":59,"symbol":"TestResponseWriterUnwrap","kind":"function","lang":"go","code":"func TestResponseWriterUnwrap(t *testing.T) {\n\ttestWriter := httptest.NewRecorder()\n\twriter := &responseWriter{ResponseWriter: testWriter}\n\tassert.Same(t, testWriter, writer.Unwrap())\n}"} {"repo":"gin","file":"response_writer_test.go","line":65,"symbol":"TestResponseWriterReset","kind":"function","lang":"go","code":"func TestResponseWriterReset(t *testing.T) {\n\ttestWriter := httptest.NewRecorder()\n\twriter := &responseWriter{}\n\tvar w ResponseWriter = writer\n\n\twriter.reset(testWriter)\n\tassert.Equal(t, -1, writer.size)\n\tassert.Equal(t, http.StatusOK, writer.status)\n\tassert.Equal(t, testWriter, writer.ResponseWriter)\n\tassert.Equal(t, -1, w.Size())\n\tassert.Equal(t, http.StatusOK, w.Status())\n\tassert.False(t, w.Written())\n}"} {"repo":"gin","file":"response_writer_test.go","line":68,"symbol":"w","kind":"variable","lang":"go","code":"w ResponseWriter = writer"} {"repo":"gin","file":"response_writer_test.go","line":79,"symbol":"TestResponseWriterWriteHeader","kind":"function","lang":"go","code":"func TestResponseWriterWriteHeader(t *testing.T) {\n\ttestWriter := httptest.NewRecorder()\n\twriter := &responseWriter{}\n\twriter.reset(testWriter)\n\tw := ResponseWriter(writer)\n\n\tw.WriteHeader(http.StatusMultipleChoices)\n\tassert.False(t, w.Written())\n\tassert.Equal(t, http.StatusMultipleChoices, w.Status())\n\tassert.NotEqual(t, http.StatusMultipleChoices, testWriter.Code)\n\n\tw.WriteHeader(-1)\n\tassert.Equal(t, http.StatusMultipleChoices, w.Status())\n}"} {"repo":"gin","file":"response_writer_test.go","line":94,"symbol":"TestResponseWriterWriteHeadersNow","kind":"function","lang":"go","code":"func TestResponseWriterWriteHeadersNow(t *testing.T) {\n\ttestWriter := httptest.NewRecorder()\n\twriter := &responseWriter{}\n\twriter.reset(testWriter)\n\tw := ResponseWriter(writer)\n\n\tw.WriteHeader(http.StatusMultipleChoices)\n\tw.WriteHeaderNow()\n\n\tassert.True(t, w.Written())\n\tassert.Equal(t, 0, w.Size())\n\tassert.Equal(t, http.StatusMultipleChoices, testWriter.Code)\n\n\twriter.size = 10\n\tw.WriteHeaderNow()\n\tassert.Equal(t, 10, w.Size())\n}"} {"repo":"gin","file":"response_writer_test.go","line":112,"symbol":"TestResponseWriterWrite","kind":"function","lang":"go","code":"func TestResponseWriterWrite(t *testing.T) {\n\ttestWriter := httptest.NewRecorder()\n\twriter := &responseWriter{}\n\twriter.reset(testWriter)\n\tw := ResponseWriter(writer)\n\n\tn, err := w.Write([]byte(\"hola\"))\n\tassert.Equal(t, 4, n)\n\tassert.Equal(t, 4, w.Size())\n\tassert.Equal(t, http.StatusOK, w.Status())\n\tassert.Equal(t, http.StatusOK, testWriter.Code)\n\tassert.Equal(t, \"hola\", testWriter.Body.String())\n\trequire.NoError(t, err)\n\n\tn, err = w.Write([]byte(\" adios\"))\n\tassert.Equal(t, 6, n)\n\tassert.Equal(t, 10, w.Size())\n\tassert.Equal(t, \"hola adios\", testWriter.Body.String())\n\trequire.NoError(t, err)\n}"} {"repo":"gin","file":"response_writer_test.go","line":133,"symbol":"TestResponseWriterHijack","kind":"function","lang":"go","code":"func TestResponseWriterHijack(t *testing.T) {\n\ttestWriter := httptest.NewRecorder()\n\twriter := &responseWriter{}\n\twriter.reset(testWriter)\n\tw := ResponseWriter(writer)\n\n\t// httptest.ResponseRecorder doesn't implement http.Hijacker; return\n\t// http.ErrNotSupported instead of panicking (#4638). On unsupported the\n\t// writer state stays untouched so the handler can still emit a normal\n\t// HTTP response as a fallback.\n\tconn, buf, err := w.Hijack()\n\tassert.Nil(t, conn)\n\tassert.Nil(t, buf)\n\trequire.ErrorIs(t, err, http.ErrNotSupported)\n\tassert.False(t, w.Written())\n\n\t// CloseNotify on a non-CloseNotifier returns nil instead of panicking.\n\tassert.Nil(t, w.CloseNotify())\n\n\tw.Flush()\n}"} {"repo":"gin","file":"response_writer_test.go","line":155,"symbol":"mockHijacker","kind":"type","lang":"go","code":"type mockHijacker struct {\n\t*httptest.ResponseRecorder\n\thijacked bool\n}"} {"repo":"gin","file":"response_writer_test.go","line":161,"symbol":"Hijack","kind":"method","lang":"go","doc":"Hijack implements the http.Hijacker interface. It just records that it was called.","code":"func (m *mockHijacker) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tm.hijacked = true\n\treturn nil, nil, nil\n}"} {"repo":"gin","file":"response_writer_test.go","line":166,"symbol":"TestResponseWriterHijackAfterWrite","kind":"function","lang":"go","code":"func TestResponseWriterHijackAfterWrite(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\taction func(w ResponseWriter) error // Action to perform before hijacking\n\t\texpectWrittenBeforeHijack bool\n\t\texpectHijackSuccess bool\n\t\texpectWrittenAfterHijack bool\n\t\texpectError error\n\t}{\n\t\t{\n\t\t\tname: \"hijack before write should succeed\",\n\t\t\taction: func(w ResponseWriter) error { return nil },\n\t\t\texpectWrittenBeforeHijack: false,\n\t\t\texpectHijackSuccess: true,\n\t\t\texpectWrittenAfterHijack: true, // Hijack itself marks the writer as written\n\t\t\texpectError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"hijack after write should fail\",\n\t\t\taction: func(w ResponseWriter) error {\n\t\t\t\t_, err := w.Write([]byte(\"test\"))\n\t\t\t\treturn err\n\t\t\t},\n\t\t\texpectWrittenBeforeHijack: true,\n\t\t\texpectHijackSuccess: false,\n\t\t\texpectWrittenAfterHijack: true,\n\t\t\texpectError: errHijackAlreadyWritten,\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\thijacker := &mockHijacker{ResponseRecorder: httptest.NewRecorder()}\n\t\t\twriter := &responseWriter{}\n\t\t\twriter.reset(hijacker)\n"} {"repo":"gin","file":"response_writer_test.go","line":225,"symbol":"TestResponseWriterHijackAfterWriteHeaderNow","kind":"function","lang":"go","doc":"TestResponseWriterHijackAfterWriteHeaderNow verifies that hijacking is allowed after WriteHeaderNow but blocked after body data is written.","code":"func TestResponseWriterHijackAfterWriteHeaderNow(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\taction func(w ResponseWriter) error\n\t\texpectWrittenBeforeHijack bool\n\t\texpectHijackSuccess bool\n\t\texpectWrittenAfterHijack bool\n\t\texpectError error\n\t}{\n\t\t{\n\t\t\tname: \"hijack after WriteHeaderNow only should succeed (websocket pattern)\",\n\t\t\taction: func(w ResponseWriter) error {\n\t\t\t\tw.WriteHeaderNow() // Simulate websocket.Accept() behavior\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\texpectWrittenBeforeHijack: true,\n\t\t\texpectHijackSuccess: true, // NEW BEHAVIOR: allow hijack after just header write\n\t\t\texpectWrittenAfterHijack: true,\n\t\t\texpectError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"hijack after WriteHeaderNow + Write should fail\",\n\t\t\taction: func(w ResponseWriter) error {\n\t\t\t\tw.WriteHeaderNow()\n\t\t\t\t_, err := w.Write([]byte(\"test\"))\n\t\t\t\treturn err\n\t\t\t},\n\t\t\texpectWrittenBeforeHijack: true,\n\t\t\texpectHijackSuccess: false,\n\t\t\texpectWrittenAfterHijack: true,\n\t\t\texpectError: errHijackAlreadyWritten,\n\t\t},\n\t}\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\thijacker := &mockHijacker{ResponseRecorder: "} {"repo":"gin","file":"response_writer_test.go","line":282,"symbol":"TestResponseWriterFlush","kind":"function","lang":"go","code":"func TestResponseWriterFlush(t *testing.T) {\n\ttestServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\twriter := &responseWriter{}\n\t\twriter.reset(w)\n\n\t\twriter.WriteHeader(http.StatusInternalServerError)\n\t\twriter.Flush()\n\t}))\n\tdefer testServer.Close()\n\n\t// should return 500\n\tresp, err := http.Get(testServer.URL)\n\trequire.NoError(t, err)\n\tassert.Equal(t, http.StatusInternalServerError, resp.StatusCode)\n}"} {"repo":"gin","file":"response_writer_test.go","line":298,"symbol":"TestResponseWriterStatusCode","kind":"function","lang":"go","code":"func TestResponseWriterStatusCode(t *testing.T) {\n\ttestWriter := httptest.NewRecorder()\n\twriter := &responseWriter{}\n\twriter.reset(testWriter)\n\tw := ResponseWriter(writer)\n\n\tw.WriteHeader(http.StatusOK)\n\tw.WriteHeaderNow()\n\n\tassert.Equal(t, http.StatusOK, w.Status())\n\tassert.True(t, w.Written())\n\n\tw.WriteHeader(http.StatusUnauthorized)\n\n\t// status must be 200 although we tried to change it\n\tassert.Equal(t, http.StatusOK, w.Status())\n}"} {"repo":"gin","file":"response_writer_test.go","line":317,"symbol":"mockPusherResponseWriter","kind":"type","lang":"go","doc":"mockPusherResponseWriter is an http.ResponseWriter that implements http.Pusher.","code":"type mockPusherResponseWriter struct {\n\thttp.ResponseWriter\n}"} {"repo":"gin","file":"response_writer_test.go","line":321,"symbol":"Push","kind":"method","lang":"go","code":"func (m *mockPusherResponseWriter) Push(target string, opts *http.PushOptions) error {\n\treturn nil\n}"} {"repo":"gin","file":"response_writer_test.go","line":326,"symbol":"nonPusherResponseWriter","kind":"type","lang":"go","doc":"nonPusherResponseWriter is an http.ResponseWriter that does not implement http.Pusher.","code":"type nonPusherResponseWriter struct {\n\thttp.ResponseWriter\n}"} {"repo":"gin","file":"response_writer_test.go","line":330,"symbol":"TestPusherWithPusher","kind":"function","lang":"go","code":"func TestPusherWithPusher(t *testing.T) {\n\trw := &mockPusherResponseWriter{}\n\tw := &responseWriter{ResponseWriter: rw}\n\n\tpusher := w.Pusher()\n\tassert.NotNil(t, pusher, \"Expected pusher to be non-nil\")\n}"} {"repo":"gin","file":"response_writer_test.go","line":338,"symbol":"TestPusherWithoutPusher","kind":"function","lang":"go","code":"func TestPusherWithoutPusher(t *testing.T) {\n\trw := &nonPusherResponseWriter{}\n\tw := &responseWriter{ResponseWriter: rw}\n\n\tpusher := w.Pusher()\n\tassert.Nil(t, pusher, \"Expected pusher to be nil\")\n}"} {"repo":"gin","file":"routergroup.go","line":17,"symbol":"MethodQuery","kind":"constant","lang":"go","doc":"MethodQuery is the HTTP QUERY method defined by RFC 10008. It is declared here because the standard library does not provide http.MethodQuery yet. Once it does, this constant keeps the same value and stays valid.","code":"MethodQuery = \"QUERY\""} {"repo":"gin","file":"routergroup.go","line":21,"symbol":"regEnLetter","kind":"variable","lang":"go","doc":"regEnLetter matches english letters for http method name","code":"regEnLetter = regexp.MustCompile(\"^[A-Z]+$\")"} {"repo":"gin","file":"routergroup.go","line":24,"symbol":"anyMethods","kind":"variable","lang":"go","doc":"anyMethods for RouterGroup Any method","code":"anyMethods = []string{\n\t\thttp.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch,\n\t\thttp.MethodHead, http.MethodOptions, http.MethodDelete, http.MethodConnect,\n\t\thttp.MethodTrace,\n\t}"} {"repo":"gin","file":"routergroup.go","line":32,"symbol":"IRouter","kind":"type","lang":"go","doc":"IRouter defines all router handle interface includes single and group router.","code":"type IRouter interface {\n\tIRoutes\n\tGroup(string, ...HandlerFunc) *RouterGroup\n}"} {"repo":"gin","file":"routergroup.go","line":38,"symbol":"IRoutes","kind":"type","lang":"go","doc":"IRoutes defines all router handle interface.","code":"type IRoutes interface {\n\tUse(...HandlerFunc) IRoutes\n\n\tHandle(string, string, ...HandlerFunc) IRoutes\n\tAny(string, ...HandlerFunc) IRoutes\n\tGET(string, ...HandlerFunc) IRoutes\n\tPOST(string, ...HandlerFunc) IRoutes\n\tDELETE(string, ...HandlerFunc) IRoutes\n\tPATCH(string, ...HandlerFunc) IRoutes\n\tPUT(string, ...HandlerFunc) IRoutes\n\tOPTIONS(string, ...HandlerFunc) IRoutes\n\tHEAD(string, ...HandlerFunc) IRoutes\n\tMatch([]string, string, ...HandlerFunc) IRoutes\n\n\tStaticFile(string, string) IRoutes\n\tStaticFileFS(string, string, http.FileSystem) IRoutes\n\tStatic(string, string) IRoutes\n\tStaticFS(string, http.FileSystem) IRoutes\n}"} {"repo":"gin","file":"routergroup.go","line":70,"symbol":"IQueryRoutes","kind":"type","lang":"go","doc":"if q, ok := routes.(gin.IQueryRoutes); ok { q.QUERY(\"/search\", handler) } *gin.RouterGroup and *gin.Engine satisfy this interface, so the assertion is only needed when the concrete type has been erased.","code":"type IQueryRoutes interface {\n\tQUERY(string, ...HandlerFunc) IRoutes\n}"} {"repo":"gin","file":"routergroup.go","line":76,"symbol":"RouterGroup","kind":"type","lang":"go","doc":"RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix and an array of handlers (middleware).","code":"type RouterGroup struct {\n\tHandlers HandlersChain\n\tbasePath string\n\tengine *Engine\n\troot bool\n}"} {"repo":"gin","file":"routergroup.go","line":84,"symbol":"_","kind":"variable","lang":"go","code":"_ IRouter = (*RouterGroup)(nil)"} {"repo":"gin","file":"routergroup.go","line":85,"symbol":"_","kind":"variable","lang":"go","code":"_ IQueryRoutes = (*RouterGroup)(nil)"} {"repo":"gin","file":"routergroup.go","line":89,"symbol":"Use","kind":"method","lang":"go","doc":"Use adds middleware to the group, see example code in GitHub.","code":"func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {\n\tgroup.Handlers = append(group.Handlers, middleware...)\n\treturn group.returnObj()\n}"} {"repo":"gin","file":"routergroup.go","line":96,"symbol":"Group","kind":"method","lang":"go","doc":"Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. For example, all the routes that use a common middleware for authorization could be grouped.","code":"func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {\n\treturn &RouterGroup{\n\t\tHandlers: group.combineHandlers(handlers),\n\t\tbasePath: group.calculateAbsolutePath(relativePath),\n\t\tengine: group.engine,\n\t}\n}"} {"repo":"gin","file":"routergroup.go","line":106,"symbol":"BasePath","kind":"method","lang":"go","doc":"BasePath returns the base path of router group. For example, if v := router.Group(\"/rest/n/v1/api\"), v.BasePath() is \"/rest/n/v1/api\".","code":"func (group *RouterGroup) BasePath() string {\n\treturn group.basePath\n}"} {"repo":"gin","file":"routergroup.go","line":110,"symbol":"handle","kind":"method","lang":"go","code":"func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {\n\tabsolutePath := group.calculateAbsolutePath(relativePath)\n\thandlers = group.combineHandlers(handlers)\n\tgroup.engine.addRoute(httpMethod, absolutePath, handlers)\n\treturn group.returnObj()\n}"} {"repo":"gin","file":"routergroup.go","line":129,"symbol":"Handle","kind":"method","lang":"go","doc":"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).","code":"func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {\n\tif matched := regEnLetter.MatchString(httpMethod); !matched {\n\t\tpanic(\"http method \" + httpMethod + \" is not valid\")\n\t}\n\treturn group.handle(httpMethod, relativePath, handlers)\n}"} {"repo":"gin","file":"routergroup.go","line":137,"symbol":"POST","kind":"method","lang":"go","doc":"POST is a shortcut for router.Handle(\"POST\", path, handlers).","code":"func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes {\n\treturn group.handle(http.MethodPost, relativePath, handlers)\n}"} {"repo":"gin","file":"routergroup.go","line":142,"symbol":"GET","kind":"method","lang":"go","doc":"GET is a shortcut for router.Handle(\"GET\", path, handlers).","code":"func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {\n\treturn group.handle(http.MethodGet, relativePath, handlers)\n}"} {"repo":"gin","file":"routergroup.go","line":147,"symbol":"DELETE","kind":"method","lang":"go","doc":"DELETE is a shortcut for router.Handle(\"DELETE\", path, handlers).","code":"func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes {\n\treturn group.handle(http.MethodDelete, relativePath, handlers)\n}"} {"repo":"gin","file":"routergroup.go","line":152,"symbol":"PATCH","kind":"method","lang":"go","doc":"PATCH is a shortcut for router.Handle(\"PATCH\", path, handlers).","code":"func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes {\n\treturn group.handle(http.MethodPatch, relativePath, handlers)\n}"} {"repo":"gin","file":"routergroup.go","line":157,"symbol":"PUT","kind":"method","lang":"go","doc":"PUT is a shortcut for router.Handle(\"PUT\", path, handlers).","code":"func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes {\n\treturn group.handle(http.MethodPut, relativePath, handlers)\n}"} {"repo":"gin","file":"routergroup.go","line":162,"symbol":"OPTIONS","kind":"method","lang":"go","doc":"OPTIONS is a shortcut for router.Handle(\"OPTIONS\", path, handlers).","code":"func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes {\n\treturn group.handle(http.MethodOptions, relativePath, handlers)\n}"} {"repo":"gin","file":"routergroup.go","line":167,"symbol":"HEAD","kind":"method","lang":"go","doc":"HEAD is a shortcut for router.Handle(\"HEAD\", path, handlers).","code":"func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes {\n\treturn group.handle(http.MethodHead, relativePath, handlers)\n}"} {"repo":"gin","file":"routergroup.go","line":176,"symbol":"QUERY","kind":"method","lang":"go","doc":"QUERY is a shortcut for router.Handle(\"QUERY\", path, handlers). QUERY is the safe and idempotent method defined by RFC 10008 that carries its query in the request body. The body is read like any other body, for example with c.ShouldBindJSON.","code":"func (group *RouterGroup) QUERY(relativePath string, handlers ...HandlerFunc) IRoutes {\n\treturn group.handle(MethodQuery, relativePath, handlers)\n}"} {"repo":"gin","file":"routergroup.go","line":186,"symbol":"Any","kind":"method","lang":"go","doc":"Any registers a route that matches all the HTTP methods. GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. QUERY is not part of that list, so that Any keeps registering exactly the same routes as before. Register it with QUERY, or with Match([]string{gin.MethodQuery, ...}, ...) to combine it with other methods.","code":"func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {\n\tfor _, method := range anyMethods {\n\t\tgroup.handle(method, relativePath, handlers)\n\t}\n\n\treturn group.returnObj()\n}"} {"repo":"gin","file":"routergroup.go","line":195,"symbol":"Match","kind":"method","lang":"go","doc":"Match registers a route that matches the specified methods that you declared.","code":"func (group *RouterGroup) Match(methods []string, relativePath string, handlers ...HandlerFunc) IRoutes {\n\tfor _, method := range methods {\n\t\tgroup.handle(method, relativePath, handlers)\n\t}\n\n\treturn group.returnObj()\n}"} {"repo":"gin","file":"routergroup.go","line":205,"symbol":"StaticFile","kind":"method","lang":"go","doc":"StaticFile registers a single route in order to serve a single file of the local filesystem. router.StaticFile(\"favicon.ico\", \"./resources/favicon.ico\")","code":"func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes {\n\treturn group.staticFileHandler(relativePath, func(c *Context) {\n\t\tc.File(filepath)\n\t})\n}"} {"repo":"gin","file":"routergroup.go","line":214,"symbol":"StaticFileFS","kind":"method","lang":"go","doc":"StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead. router.StaticFileFS(\"favicon.ico\", \"./resources/favicon.ico\", Dir{\".\", false}) Gin by default uses: gin.Dir()","code":"func (group *RouterGroup) StaticFileFS(relativePath, filepath string, fs http.FileSystem) IRoutes {\n\treturn group.staticFileHandler(relativePath, func(c *Context) {\n\t\tc.FileFromFS(filepath, fs)\n\t})\n}"} {"repo":"gin","file":"routergroup.go","line":220,"symbol":"staticFileHandler","kind":"method","lang":"go","code":"func (group *RouterGroup) staticFileHandler(relativePath string, handler HandlerFunc) IRoutes {\n\tif strings.Contains(relativePath, \":\") || strings.Contains(relativePath, \"*\") {\n\t\tpanic(\"URL parameters can not be used when serving a static file\")\n\t}\n\tgroup.GET(relativePath, handler)\n\tgroup.HEAD(relativePath, handler)\n\treturn group.returnObj()\n}"} {"repo":"gin","file":"routergroup.go","line":236,"symbol":"Static","kind":"method","lang":"go","doc":"Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use : router.Static(\"/static\", \"/var/www\")","code":"func (group *RouterGroup) Static(relativePath, root string) IRoutes {\n\treturn group.StaticFS(relativePath, Dir(root, false))\n}"} {"repo":"gin","file":"routergroup.go","line":243,"symbol":"StaticFS","kind":"method","lang":"go","doc":"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 *).","code":"func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes {\n\tif strings.Contains(relativePath, \":\") || strings.Contains(relativePath, \"*\") {\n\t\tpanic(\"URL parameters can not be used when serving a static folder\")\n\t}\n\thandler := group.createStaticHandler(relativePath, fs)\n\turlPattern := path.Join(relativePath, \"/*filepath\")\n\n\t// Register GET and HEAD handlers\n\tgroup.GET(urlPattern, handler)\n\tgroup.HEAD(urlPattern, handler)\n\treturn group.returnObj()\n}"} {"repo":"gin","file":"routergroup.go","line":256,"symbol":"createStaticHandler","kind":"method","lang":"go","code":"func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {\n\tabsolutePath := group.calculateAbsolutePath(relativePath)\n\tfileServer := http.StripPrefix(absolutePath, http.FileServer(fs))\n\n\treturn func(c *Context) {\n\t\tif _, noListing := fs.(*OnlyFilesFS); noListing {\n\t\t\tc.Writer.WriteHeader(http.StatusNotFound)\n\t\t}\n\n\t\tfile := c.Param(\"filepath\")\n\t\t// Check if file exists and/or if we have permission to access it\n\t\tf, err := fs.Open(file)\n\t\tif err != nil {\n\t\t\tc.Writer.WriteHeader(http.StatusNotFound)\n\t\t\tc.handlers = group.engine.noRoute\n\t\t\t// Reset index\n\t\t\tc.index = -1\n\t\t\treturn\n\t\t}\n\t\tf.Close()\n\n\t\tfileServer.ServeHTTP(c.Writer, c.Request)\n\t}\n}"} {"repo":"gin","file":"routergroup.go","line":281,"symbol":"combineHandlers","kind":"method","lang":"go","code":"func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {\n\tfinalSize := len(group.Handlers) + len(handlers)\n\tassert1(finalSize < int(abortIndex), \"too many handlers\")\n\tmergedHandlers := make(HandlersChain, finalSize)\n\tcopy(mergedHandlers, group.Handlers)\n\tcopy(mergedHandlers[len(group.Handlers):], handlers)\n\treturn mergedHandlers\n}"} {"repo":"gin","file":"routergroup.go","line":290,"symbol":"calculateAbsolutePath","kind":"method","lang":"go","code":"func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {\n\treturn joinPaths(group.basePath, relativePath)\n}"} {"repo":"gin","file":"routergroup.go","line":294,"symbol":"returnObj","kind":"method","lang":"go","code":"func (group *RouterGroup) returnObj() IRoutes {\n\tif group.root {\n\t\treturn group.engine\n\t}\n\treturn group\n}"} {"repo":"gin","file":"routergroup_test.go","line":14,"symbol":"MaxHandlers","kind":"variable","lang":"go","code":"MaxHandlers = 32"} {"repo":"gin","file":"routergroup_test.go","line":16,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tSetMode(TestMode)\n}"} {"repo":"gin","file":"routergroup_test.go","line":20,"symbol":"TestRouterGroupBasic","kind":"function","lang":"go","code":"func TestRouterGroupBasic(t *testing.T) {\n\trouter := New()\n\tgroup := router.Group(\"/hola\", func(c *Context) {})\n\tgroup.Use(func(c *Context) {})\n\n\tassert.Len(t, group.Handlers, 2)\n\tassert.Equal(t, \"/hola\", group.BasePath())\n\tassert.Equal(t, router, group.engine)\n\n\tgroup2 := group.Group(\"manu\")\n\tgroup2.Use(func(c *Context) {}, func(c *Context) {})\n\n\tassert.Len(t, group2.Handlers, 4)\n\tassert.Equal(t, \"/hola/manu\", group2.BasePath())\n\tassert.Equal(t, router, group2.engine)\n}"} {"repo":"gin","file":"routergroup_test.go","line":37,"symbol":"TestRouterGroupBasicHandle","kind":"function","lang":"go","code":"func TestRouterGroupBasicHandle(t *testing.T) {\n\tperformRequestInGroup(t, http.MethodGet)\n\tperformRequestInGroup(t, http.MethodPost)\n\tperformRequestInGroup(t, http.MethodPut)\n\tperformRequestInGroup(t, http.MethodPatch)\n\tperformRequestInGroup(t, http.MethodDelete)\n\tperformRequestInGroup(t, http.MethodHead)\n\tperformRequestInGroup(t, http.MethodOptions)\n\tperformRequestInGroup(t, MethodQuery)\n}"} {"repo":"gin","file":"routergroup_test.go","line":48,"symbol":"performRequestInGroup","kind":"function","lang":"go","code":"func performRequestInGroup(t *testing.T, method string) {\n\trouter := New()\n\tv1 := router.Group(\"v1\", func(c *Context) {})\n\tassert.Equal(t, \"/v1\", v1.BasePath())\n\n\tlogin := v1.Group(\"/login/\", func(c *Context) {}, func(c *Context) {})\n\tassert.Equal(t, \"/v1/login/\", login.BasePath())\n\n\thandler := func(c *Context) {\n\t\tc.String(http.StatusBadRequest, \"the method was %s and index %d\", c.Request.Method, c.index)\n\t}\n\n\tswitch method {\n\tcase http.MethodGet:\n\t\tv1.GET(\"/test\", handler)\n\t\tlogin.GET(\"/test\", handler)\n\tcase http.MethodPost:\n\t\tv1.POST(\"/test\", handler)\n\t\tlogin.POST(\"/test\", handler)\n\tcase http.MethodPut:\n\t\tv1.PUT(\"/test\", handler)\n\t\tlogin.PUT(\"/test\", handler)\n\tcase http.MethodPatch:\n\t\tv1.PATCH(\"/test\", handler)\n\t\tlogin.PATCH(\"/test\", handler)\n\tcase http.MethodDelete:\n\t\tv1.DELETE(\"/test\", handler)\n\t\tlogin.DELETE(\"/test\", handler)\n\tcase http.MethodHead:\n\t\tv1.HEAD(\"/test\", handler)\n\t\tlogin.HEAD(\"/test\", handler)\n\tcase http.MethodOptions:\n\t\tv1.OPTIONS(\"/test\", handler)\n\t\tlogin.OPTIONS(\"/test\", handler)\n\tcase MethodQuery:\n\t\tv1.QUERY(\"/test\", handler)\n\t\tlogin.QUERY(\"/test\", handler)\n\tdefault:\n\t\tpanic(\"unknown method\")\n\t}\n\n\tw := PerformRequest(router, method, \"/v1/login/test\")\n\tassert."} {"repo":"gin","file":"routergroup_test.go","line":98,"symbol":"TestRouterGroupInvalidStatic","kind":"function","lang":"go","code":"func TestRouterGroupInvalidStatic(t *testing.T) {\n\trouter := New()\n\tassert.Panics(t, func() {\n\t\trouter.Static(\"/path/:param\", \"/\")\n\t})\n\n\tassert.Panics(t, func() {\n\t\trouter.Static(\"/path/*param\", \"/\")\n\t})\n}"} {"repo":"gin","file":"routergroup_test.go","line":109,"symbol":"TestRouterGroupInvalidStaticFile","kind":"function","lang":"go","code":"func TestRouterGroupInvalidStaticFile(t *testing.T) {\n\trouter := New()\n\tassert.Panics(t, func() {\n\t\trouter.StaticFile(\"/path/:param\", \"favicon.ico\")\n\t})\n\n\tassert.Panics(t, func() {\n\t\trouter.StaticFile(\"/path/*param\", \"favicon.ico\")\n\t})\n}"} {"repo":"gin","file":"routergroup_test.go","line":120,"symbol":"TestRouterGroupInvalidStaticFileFS","kind":"function","lang":"go","code":"func TestRouterGroupInvalidStaticFileFS(t *testing.T) {\n\trouter := New()\n\tassert.Panics(t, func() {\n\t\trouter.StaticFileFS(\"/path/:param\", \"favicon.ico\", Dir(\".\", false))\n\t})\n\n\tassert.Panics(t, func() {\n\t\trouter.StaticFileFS(\"/path/*param\", \"favicon.ico\", Dir(\".\", false))\n\t})\n}"} {"repo":"gin","file":"routergroup_test.go","line":131,"symbol":"TestRouterGroupTooManyHandlers","kind":"function","lang":"go","code":"func TestRouterGroupTooManyHandlers(t *testing.T) {\n\tconst (\n\t\tpanicValue = \"too many handlers\"\n\t\tmaximumCnt = abortIndex\n\t)\n\trouter := New()\n\thandlers1 := make([]HandlerFunc, maximumCnt-1)\n\trouter.Use(handlers1...)\n\n\thandlers2 := make([]HandlerFunc, maximumCnt+1)\n\tassert.PanicsWithValue(t, panicValue, func() {\n\t\trouter.Use(handlers2...)\n\t})\n\tassert.PanicsWithValue(t, panicValue, func() {\n\t\trouter.GET(\"/\", handlers2...)\n\t})\n}"} {"repo":"gin","file":"routergroup_test.go","line":133,"symbol":"panicValue","kind":"constant","lang":"go","code":"panicValue = \"too many handlers\""} {"repo":"gin","file":"routergroup_test.go","line":134,"symbol":"maximumCnt","kind":"constant","lang":"go","code":"maximumCnt = abortIndex"} {"repo":"gin","file":"routergroup_test.go","line":149,"symbol":"TestRouterGroupBadMethod","kind":"function","lang":"go","code":"func TestRouterGroupBadMethod(t *testing.T) {\n\trouter := New()\n\tassert.Panics(t, func() {\n\t\trouter.Handle(http.MethodGet, \"/\")\n\t})\n\tassert.Panics(t, func() {\n\t\trouter.Handle(\" GET\", \"/\")\n\t})\n\tassert.Panics(t, func() {\n\t\trouter.Handle(\"GET \", \"/\")\n\t})\n\tassert.Panics(t, func() {\n\t\trouter.Handle(\"\", \"/\")\n\t})\n\tassert.Panics(t, func() {\n\t\trouter.Handle(\"PO ST\", \"/\")\n\t})\n\tassert.Panics(t, func() {\n\t\trouter.Handle(\"1GET\", \"/\")\n\t})\n\tassert.Panics(t, func() {\n\t\trouter.Handle(\"PATCh\", \"/\")\n\t})\n}"} {"repo":"gin","file":"routergroup_test.go","line":174,"symbol":"TestRouterGroupPipeline","kind":"function","lang":"go","code":"func TestRouterGroupPipeline(t *testing.T) {\n\trouter := New()\n\ttestRoutesInterface(t, router)\n\n\tv1 := router.Group(\"/v1\")\n\ttestRoutesInterface(t, v1)\n}"} {"repo":"gin","file":"routergroup_test.go","line":182,"symbol":"testRoutesInterface","kind":"function","lang":"go","code":"func testRoutesInterface(t *testing.T, r IRoutes) {\n\thandler := func(c *Context) {}\n\tassert.Equal(t, r, r.Use(handler))\n\n\tassert.Equal(t, r, r.Handle(http.MethodGet, \"/handler\", handler))\n\tassert.Equal(t, r, r.Any(\"/any\", handler))\n\tassert.Equal(t, r, r.GET(\"/\", handler))\n\tassert.Equal(t, r, r.POST(\"/\", handler))\n\tassert.Equal(t, r, r.DELETE(\"/\", handler))\n\tassert.Equal(t, r, r.PATCH(\"/\", handler))\n\tassert.Equal(t, r, r.PUT(\"/\", handler))\n\tassert.Equal(t, r, r.OPTIONS(\"/\", handler))\n\tassert.Equal(t, r, r.HEAD(\"/\", handler))\n\tassert.Equal(t, r, r.Match([]string{http.MethodPut, http.MethodPatch}, \"/match\", handler))\n\n\tassert.Equal(t, r, r.StaticFile(\"/file\", \".\"))\n\tassert.Equal(t, r, r.StaticFileFS(\"/static2\", \".\", Dir(\".\", false)))\n\tassert.Equal(t, r, r.Static(\"/static\", \".\"))\n\tassert.Equal(t, r, r.StaticFS(\"/static2\", Dir(\".\", false)))\n}"} {"repo":"gin","file":"routergroup_test.go","line":203,"symbol":"TestRouterGroupCombineHandlersTooManyHandlers","kind":"function","lang":"go","code":"func TestRouterGroupCombineHandlersTooManyHandlers(t *testing.T) {\n\tgroup := &RouterGroup{\n\t\tHandlers: make(HandlersChain, MaxHandlers), // Assume group already has MaxHandlers middleware\n\t}\n\ttooManyHandlers := make(HandlersChain, MaxHandlers) // Add MaxHandlers more, total 2 * MaxHandlers\n\n\t// This should trigger panic\n\tassert.Panics(t, func() {\n\t\tgroup.combineHandlers(tooManyHandlers)\n\t}, \"should panic due to too many handlers\")\n}"} {"repo":"gin","file":"routergroup_test.go","line":215,"symbol":"TestRouterGroupCombineHandlersEmptySliceNotNil","kind":"function","lang":"go","code":"func TestRouterGroupCombineHandlersEmptySliceNotNil(t *testing.T) {\n\tgroup := &RouterGroup{\n\t\tHandlers: HandlersChain{},\n\t}\n\n\tresult := group.combineHandlers(HandlersChain{})\n\tassert.NotNil(t, result, \"result should not be nil even with empty handlers\")\n\tassert.Empty(t, result, \"empty handlers should return empty chain\")\n}"} {"repo":"gin","file":"routes_test.go","line":20,"symbol":"header","kind":"type","lang":"go","code":"type header struct {\n\tKey string\n\tValue string\n}"} {"repo":"gin","file":"routes_test.go","line":26,"symbol":"PerformRequest","kind":"function","lang":"go","doc":"PerformRequest for testing gin router.","code":"func PerformRequest(r http.Handler, method, path string, headers ...header) *httptest.ResponseRecorder {\n\treq := httptest.NewRequest(method, path, nil)\n\tfor _, h := range headers {\n\t\treq.Header.Add(h.Key, h.Value)\n\t}\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\treturn w\n}"} {"repo":"gin","file":"routes_test.go","line":36,"symbol":"testRouteOK","kind":"function","lang":"go","code":"func testRouteOK(method string, t *testing.T) {\n\tpassed := false\n\tpassedAny := false\n\tr := New()\n\tr.Any(\"/test2\", func(c *Context) {\n\t\tpassedAny = true\n\t})\n\tr.Handle(method, \"/test\", func(c *Context) {\n\t\tpassed = true\n\t})\n\n\tw := PerformRequest(r, method, \"/test\")\n\tassert.True(t, passed)\n\tassert.Equal(t, http.StatusOK, w.Code)\n\n\tPerformRequest(r, method, \"/test2\")\n\tassert.True(t, passedAny)\n}"} {"repo":"gin","file":"routes_test.go","line":56,"symbol":"testRouteNotOK","kind":"function","lang":"go","doc":"testRouteNotOK tests that a request with the wrong method returns a not found response.","code":"func testRouteNotOK(method string, t *testing.T) {\n\tpassed := false\n\trouter := New()\n\trouter.Handle(method, \"/test_2\", func(c *Context) {\n\t\tpassed = true\n\t})\n\n\tw := PerformRequest(router, method, \"/test\")\n\n\tassert.False(t, passed)\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":70,"symbol":"testRouteNotOK2","kind":"function","lang":"go","doc":"testRouteNotOK2 tests that a request with the wrong method returns a method not allowed response.","code":"func testRouteNotOK2(method string, t *testing.T) {\n\tpassed := false\n\trouter := New()\n\trouter.HandleMethodNotAllowed = true\n\tvar methodRoute string\n\tif method == http.MethodPost {\n\t\tmethodRoute = http.MethodGet\n\t} else {\n\t\tmethodRoute = http.MethodPost\n\t}\n\trouter.Handle(methodRoute, \"/test\", func(c *Context) {\n\t\tpassed = true\n\t})\n\n\tw := PerformRequest(router, method, \"/test\")\n\n\tassert.False(t, passed)\n\tassert.Equal(t, http.StatusMethodNotAllowed, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":74,"symbol":"methodRoute","kind":"variable","lang":"go","code":"methodRoute string"} {"repo":"gin","file":"routes_test.go","line":92,"symbol":"TestRouteQuery","kind":"function","lang":"go","doc":"TestRouteQuery tests that a QUERY route is invoked and can read the request body, which is the whole point of the method (RFC 10008).","code":"func TestRouteQuery(t *testing.T) {\n\ttype search struct {\n\t\tTerm string `json:\"term\"`\n\t}\n\n\trouter := New()\n\trouter.QUERY(\"/search\", func(c *Context) {\n\t\tvar body search\n\t\trequire.NoError(t, c.ShouldBindJSON(&body))\n\t\tc.String(http.StatusOK, body.Term)\n\t})\n\n\treq := httptest.NewRequest(MethodQuery, \"/search\", strings.NewReader(`{\"term\":\"gin\"}`))\n\treq.Header.Set(\"Content-Type\", MIMEJSON)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"gin\", w.Body.String())\n}"} {"repo":"gin","file":"routes_test.go","line":93,"symbol":"search","kind":"type","lang":"go","code":"type search struct {\n\t\tTerm string `json:\"term\"`\n\t}"} {"repo":"gin","file":"routes_test.go","line":99,"symbol":"body","kind":"variable","lang":"go","code":"body search"} {"repo":"gin","file":"routes_test.go","line":115,"symbol":"TestRouteQueryNotRegisteredByAny","kind":"function","lang":"go","doc":"TestRouteQueryNotRegisteredByAny documents that Any does not register QUERY, so that existing Any routes keep matching exactly the methods they used to.","code":"func TestRouteQueryNotRegisteredByAny(t *testing.T) {\n\trouter := New()\n\trouter.Any(\"/test\", func(c *Context) {\n\t\tc.Status(http.StatusOK)\n\t})\n\n\tw := PerformRequest(router, MethodQuery, \"/test\")\n\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":128,"symbol":"TestQueryRoutesInterface","kind":"function","lang":"go","doc":"TestQueryRoutesInterface tests that a router reached through IRoutes can still register a QUERY route via the IQueryRoutes assertion.","code":"func TestQueryRoutesInterface(t *testing.T) {\n\trouter := New()\n\n\tvar routes IRoutes = router.Group(\"/v1\")\n\tqueryRoutes, ok := routes.(IQueryRoutes)\n\trequire.True(t, ok)\n\n\tqueryRoutes.QUERY(\"/search\", func(c *Context) {\n\t\tc.Status(http.StatusOK)\n\t})\n\n\tw := PerformRequest(router, MethodQuery, \"/v1/search\")\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":131,"symbol":"routes","kind":"variable","lang":"go","code":"routes IRoutes = router.Group(\"/v1\")"} {"repo":"gin","file":"routes_test.go","line":144,"symbol":"TestRouterMethod","kind":"function","lang":"go","code":"func TestRouterMethod(t *testing.T) {\n\trouter := New()\n\trouter.PUT(\"/hey2\", func(c *Context) {\n\t\tc.String(http.StatusOK, \"sup2\")\n\t})\n\n\trouter.PUT(\"/hey\", func(c *Context) {\n\t\tc.String(http.StatusOK, \"called\")\n\t})\n\n\trouter.PUT(\"/hey3\", func(c *Context) {\n\t\tc.String(http.StatusOK, \"sup3\")\n\t})\n\n\tw := PerformRequest(router, http.MethodPut, \"/hey\")\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"called\", w.Body.String())\n}"} {"repo":"gin","file":"routes_test.go","line":164,"symbol":"TestRouterGroupRouteOK","kind":"function","lang":"go","code":"func TestRouterGroupRouteOK(t *testing.T) {\n\ttestRouteOK(http.MethodGet, t)\n\ttestRouteOK(http.MethodPost, t)\n\ttestRouteOK(http.MethodPut, t)\n\ttestRouteOK(http.MethodPatch, t)\n\ttestRouteOK(http.MethodHead, t)\n\ttestRouteOK(http.MethodOptions, t)\n\ttestRouteOK(http.MethodDelete, t)\n\ttestRouteOK(http.MethodConnect, t)\n\ttestRouteOK(http.MethodTrace, t)\n}"} {"repo":"gin","file":"routes_test.go","line":176,"symbol":"TestRouteNotOK","kind":"function","lang":"go","code":"func TestRouteNotOK(t *testing.T) {\n\ttestRouteNotOK(http.MethodGet, t)\n\ttestRouteNotOK(http.MethodPost, t)\n\ttestRouteNotOK(http.MethodPut, t)\n\ttestRouteNotOK(http.MethodPatch, t)\n\ttestRouteNotOK(http.MethodHead, t)\n\ttestRouteNotOK(http.MethodOptions, t)\n\ttestRouteNotOK(http.MethodDelete, t)\n\ttestRouteNotOK(http.MethodConnect, t)\n\ttestRouteNotOK(http.MethodTrace, t)\n}"} {"repo":"gin","file":"routes_test.go","line":188,"symbol":"TestRouteNotOK2","kind":"function","lang":"go","code":"func TestRouteNotOK2(t *testing.T) {\n\ttestRouteNotOK2(http.MethodGet, t)\n\ttestRouteNotOK2(http.MethodPost, t)\n\ttestRouteNotOK2(http.MethodPut, t)\n\ttestRouteNotOK2(http.MethodPatch, t)\n\ttestRouteNotOK2(http.MethodHead, t)\n\ttestRouteNotOK2(http.MethodOptions, t)\n\ttestRouteNotOK2(http.MethodDelete, t)\n\ttestRouteNotOK2(http.MethodConnect, t)\n\ttestRouteNotOK2(http.MethodTrace, t)\n}"} {"repo":"gin","file":"routes_test.go","line":200,"symbol":"TestRouteRedirectTrailingSlash","kind":"function","lang":"go","code":"func TestRouteRedirectTrailingSlash(t *testing.T) {\n\trouter := New()\n\trouter.RedirectFixedPath = false\n\trouter.RedirectTrailingSlash = true\n\trouter.GET(\"/path\", func(c *Context) {})\n\trouter.GET(\"/path2/\", func(c *Context) {})\n\trouter.POST(\"/path3\", func(c *Context) {})\n\trouter.PUT(\"/path4/\", func(c *Context) {})\n\n\tw := PerformRequest(router, http.MethodGet, \"/path/\")\n\tassert.Equal(t, \"/path\", w.Header().Get(\"Location\"))\n\tassert.Equal(t, http.StatusMovedPermanently, w.Code)\n\n\tw = PerformRequest(router, http.MethodGet, \"/path2\")\n\tassert.Equal(t, \"/path2/\", w.Header().Get(\"Location\"))\n\tassert.Equal(t, http.StatusMovedPermanently, w.Code)\n\n\tw = PerformRequest(router, http.MethodPost, \"/path3/\")\n\tassert.Equal(t, \"/path3\", w.Header().Get(\"Location\"))\n\tassert.Equal(t, http.StatusTemporaryRedirect, w.Code)\n\n\tw = PerformRequest(router, http.MethodPut, \"/path4\")\n\tassert.Equal(t, \"/path4/\", w.Header().Get(\"Location\"))\n\tassert.Equal(t, http.StatusTemporaryRedirect, w.Code)\n\n\tw = PerformRequest(router, http.MethodGet, \"/path\")\n\tassert.Equal(t, http.StatusOK, w.Code)\n\n\tw = PerformRequest(router, http.MethodGet, \"/path2/\")\n\tassert.Equal(t, http.StatusOK, w.Code)\n\n\tw = PerformRequest(router, http."} {"repo":"gin","file":"routes_test.go","line":304,"symbol":"TestRouteRedirectFixedPath","kind":"function","lang":"go","code":"func TestRouteRedirectFixedPath(t *testing.T) {\n\trouter := New()\n\trouter.RedirectFixedPath = true\n\trouter.RedirectTrailingSlash = false\n\n\trouter.GET(\"/path\", func(c *Context) {})\n\trouter.GET(\"/Path2\", func(c *Context) {})\n\trouter.POST(\"/PATH3\", func(c *Context) {})\n\trouter.POST(\"/Path4/\", func(c *Context) {})\n\n\tw := PerformRequest(router, http.MethodGet, \"/PATH\")\n\tassert.Equal(t, \"/path\", w.Header().Get(\"Location\"))\n\tassert.Equal(t, http.StatusMovedPermanently, w.Code)\n\n\tw = PerformRequest(router, http.MethodGet, \"/path2\")\n\tassert.Equal(t, \"/Path2\", w.Header().Get(\"Location\"))\n\tassert.Equal(t, http.StatusMovedPermanently, w.Code)\n\n\tw = PerformRequest(router, http.MethodPost, \"/path3\")\n\tassert.Equal(t, \"/PATH3\", w.Header().Get(\"Location\"))\n\tassert.Equal(t, http.StatusTemporaryRedirect, w.Code)\n\n\tw = PerformRequest(router, http.MethodPost, \"/path4\")\n\tassert.Equal(t, \"/Path4/\", w.Header().Get(\"Location\"))\n\tassert.Equal(t, http.StatusTemporaryRedirect, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":332,"symbol":"TestRouteParamsByName","kind":"function","lang":"go","doc":"TestRouteParamsByName tests that route parameters can be parsed by name.","code":"func TestRouteParamsByName(t *testing.T) {\n\tname := \"\"\n\tlastName := \"\"\n\twild := \"\"\n\trouter := New()\n\trouter.GET(\"/test/:name/:last_name/*wild\", func(c *Context) {\n\t\tname = c.Params.ByName(\"name\")\n\t\tlastName = c.Params.ByName(\"last_name\")\n\t\tvar ok bool\n\t\twild, ok = c.Params.Get(\"wild\")\n\n\t\tassert.True(t, ok)\n\t\tassert.Equal(t, name, c.Param(\"name\"))\n\t\tassert.Equal(t, lastName, c.Param(\"last_name\"))\n\n\t\tassert.Empty(t, c.Param(\"wtf\"))\n\t\tassert.Empty(t, c.Params.ByName(\"wtf\"))\n\n\t\twtf, ok := c.Params.Get(\"wtf\")\n\t\tassert.Empty(t, wtf)\n\t\tassert.False(t, ok)\n\t})\n\n\tw := PerformRequest(router, http.MethodGet, \"/test/john/smith/is/super/great\")\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"john\", name)\n\tassert.Equal(t, \"smith\", lastName)\n\tassert.Equal(t, \"/is/super/great\", wild)\n}"} {"repo":"gin","file":"routes_test.go","line":340,"symbol":"ok","kind":"variable","lang":"go","code":"ok bool"} {"repo":"gin","file":"routes_test.go","line":364,"symbol":"TestRouteParamsByNameWithExtraSlash","kind":"function","lang":"go","doc":"TestRouteParamsByNameWithExtraSlash tests that route parameters can be parsed by name even with extra slashes.","code":"func TestRouteParamsByNameWithExtraSlash(t *testing.T) {\n\tname := \"\"\n\tlastName := \"\"\n\twild := \"\"\n\trouter := New()\n\trouter.RemoveExtraSlash = true\n\trouter.GET(\"/test/:name/:last_name/*wild\", func(c *Context) {\n\t\tname = c.Params.ByName(\"name\")\n\t\tlastName = c.Params.ByName(\"last_name\")\n\t\tvar ok bool\n\t\twild, ok = c.Params.Get(\"wild\")\n\n\t\tassert.True(t, ok)\n\t\tassert.Equal(t, name, c.Param(\"name\"))\n\t\tassert.Equal(t, lastName, c.Param(\"last_name\"))\n\n\t\tassert.Empty(t, c.Param(\"wtf\"))\n\t\tassert.Empty(t, c.Params.ByName(\"wtf\"))\n\n\t\twtf, ok := c.Params.Get(\"wtf\")\n\t\tassert.Empty(t, wtf)\n\t\tassert.False(t, ok)\n\t})\n\n\tw := PerformRequest(router, http.MethodGet, \"//test//john//smith//is//super//great\")\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"john\", name)\n\tassert.Equal(t, \"smith\", lastName)\n\tassert.Equal(t, \"/is/super/great\", wild)\n}"} {"repo":"gin","file":"routes_test.go","line":373,"symbol":"ok","kind":"variable","lang":"go","code":"ok bool"} {"repo":"gin","file":"routes_test.go","line":399,"symbol":"TestRouteParamsNotEmpty","kind":"function","lang":"go","doc":"TestRouteParamsNotEmpty tests that context parameters will be set even if a route with params/wildcards is registered after the context initialisation (which happened in a previous requests).","code":"func TestRouteParamsNotEmpty(t *testing.T) {\n\tname := \"\"\n\tlastName := \"\"\n\twild := \"\"\n\trouter := New()\n\n\tw := PerformRequest(router, http.MethodGet, \"/test/john/smith/is/super/great\")\n\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n\n\trouter.GET(\"/test/:name/:last_name/*wild\", func(c *Context) {\n\t\tname = c.Params.ByName(\"name\")\n\t\tlastName = c.Params.ByName(\"last_name\")\n\t\tvar ok bool\n\t\twild, ok = c.Params.Get(\"wild\")\n\n\t\tassert.True(t, ok)\n\t\tassert.Equal(t, name, c.Param(\"name\"))\n\t\tassert.Equal(t, lastName, c.Param(\"last_name\"))\n\n\t\tassert.Empty(t, c.Param(\"wtf\"))\n\t\tassert.Empty(t, c.Params.ByName(\"wtf\"))\n\n\t\twtf, ok := c.Params.Get(\"wtf\")\n\t\tassert.Empty(t, wtf)\n\t\tassert.False(t, ok)\n\t})\n\n\tw = PerformRequest(router, http.MethodGet, \"/test/john/smith/is/super/great\")\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"john\", name)\n\tassert.Equal(t, \"smith\", lastName)\n\tassert.Equal(t, \"/is/super/great\", wild)\n}"} {"repo":"gin","file":"routes_test.go","line":412,"symbol":"ok","kind":"variable","lang":"go","code":"ok bool"} {"repo":"gin","file":"routes_test.go","line":436,"symbol":"TestRouteStaticFile","kind":"function","lang":"go","doc":"TestRouteStaticFile tests that a static file is served correctly.","code":"func TestRouteStaticFile(t *testing.T) {\n\t// SETUP file\n\ttestRoot, _ := os.Getwd()\n\tf, err := os.CreateTemp(testRoot, \"\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer os.Remove(f.Name())\n\t_, err = f.WriteString(\"Gin Web Framework\")\n\trequire.NoError(t, err)\n\tf.Close()\n\n\tdir, filename := filepath.Split(f.Name())\n\n\t// SETUP gin\n\trouter := New()\n\trouter.Static(\"/using_static\", dir)\n\trouter.StaticFile(\"/result\", f.Name())\n\n\tw := PerformRequest(router, http.MethodGet, \"/using_static/\"+filename)\n\tw2 := PerformRequest(router, http.MethodGet, \"/result\")\n\n\tassert.Equal(t, w, w2)\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"Gin Web Framework\", w.Body.String())\n\tassert.Equal(t, \"text/plain; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\n\tw3 := PerformRequest(router, http.MethodHead, \"/using_static/\"+filename)\n\tw4 := PerformRequest(router, http.MethodHead, \"/result\")\n\n\tassert.Equal(t, w3, w4)\n\tassert.Equal(t, http.StatusOK, w3.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":471,"symbol":"TestRouteStaticFileFS","kind":"function","lang":"go","doc":"TestRouteStaticFileFS tests that a static file from an http.FileSystem is served correctly.","code":"func TestRouteStaticFileFS(t *testing.T) {\n\t// SETUP file\n\ttestRoot, _ := os.Getwd()\n\tf, err := os.CreateTemp(testRoot, \"\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tdefer os.Remove(f.Name())\n\t_, err = f.WriteString(\"Gin Web Framework\")\n\trequire.NoError(t, err)\n\tf.Close()\n\n\tdir, filename := filepath.Split(f.Name())\n\t// SETUP gin\n\trouter := New()\n\trouter.Static(\"/using_static\", dir)\n\trouter.StaticFileFS(\"/result_fs\", filename, Dir(dir, false))\n\n\tw := PerformRequest(router, http.MethodGet, \"/using_static/\"+filename)\n\tw2 := PerformRequest(router, http.MethodGet, \"/result_fs\")\n\n\tassert.Equal(t, w, w2)\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Equal(t, \"Gin Web Framework\", w.Body.String())\n\tassert.Equal(t, \"text/plain; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n\n\tw3 := PerformRequest(router, http.MethodHead, \"/using_static/\"+filename)\n\tw4 := PerformRequest(router, http.MethodHead, \"/result_fs\")\n\n\tassert.Equal(t, w3, w4)\n\tassert.Equal(t, http.StatusOK, w3.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":505,"symbol":"TestRouteStaticListingDir","kind":"function","lang":"go","doc":"TestRouteStaticListingDir tests that static directory listing is enabled when configured.","code":"func TestRouteStaticListingDir(t *testing.T) {\n\trouter := New()\n\trouter.StaticFS(\"/\", Dir(\"./\", true))\n\n\tw := PerformRequest(router, http.MethodGet, \"/\")\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Contains(t, w.Body.String(), \"gin.go\")\n\tassert.Equal(t, \"text/html; charset=utf-8\", w.Header().Get(\"Content-Type\"))\n}"} {"repo":"gin","file":"routes_test.go","line":517,"symbol":"TestRouteStaticNoListing","kind":"function","lang":"go","doc":"TestRouteStaticNoListing tests that static directory listing is disabled by default.","code":"func TestRouteStaticNoListing(t *testing.T) {\n\trouter := New()\n\trouter.Static(\"/\", \"./\")\n\n\tw := PerformRequest(router, http.MethodGet, \"/\")\n\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n\tassert.NotContains(t, w.Body.String(), \"gin.go\")\n}"} {"repo":"gin","file":"routes_test.go","line":527,"symbol":"TestRouterMiddlewareAndStatic","kind":"function","lang":"go","code":"func TestRouterMiddlewareAndStatic(t *testing.T) {\n\trouter := New()\n\tstatic := router.Group(\"/\", func(c *Context) {\n\t\tc.Writer.Header().Add(\"Last-Modified\", \"Mon, 02 Jan 2006 15:04:05 MST\")\n\t\tc.Writer.Header().Add(\"Expires\", \"Mon, 02 Jan 2006 15:04:05 MST\")\n\t\tc.Writer.Header().Add(\"X-GIN\", \"Gin Framework\")\n\t})\n\tstatic.Static(\"/\", \"./\")\n\n\tw := PerformRequest(router, http.MethodGet, \"/gin.go\")\n\n\tassert.Equal(t, http.StatusOK, w.Code)\n\tassert.Contains(t, w.Body.String(), \"package gin\")\n\t// Content-Type='text/plain; charset=utf-8' when go version <= 1.16,\n\t// else, Content-Type='text/x-go; charset=utf-8'\n\tassert.NotEmpty(t, w.Header().Get(\"Content-Type\"))\n\tassert.NotEqual(t, \"Mon, 02 Jan 2006 15:04:05 MST\", w.Header().Get(\"Last-Modified\"))\n\tassert.Equal(t, \"Mon, 02 Jan 2006 15:04:05 MST\", w.Header().Get(\"Expires\"))\n\tassert.Equal(t, \"Gin Framework\", w.Header().Get(\"x-GIN\"))\n}"} {"repo":"gin","file":"routes_test.go","line":548,"symbol":"TestRouteNotAllowedEnabled","kind":"function","lang":"go","code":"func TestRouteNotAllowedEnabled(t *testing.T) {\n\trouter := New()\n\trouter.HandleMethodNotAllowed = true\n\trouter.POST(\"/path\", func(c *Context) {})\n\tw := PerformRequest(router, http.MethodGet, \"/path\")\n\tassert.Equal(t, http.StatusMethodNotAllowed, w.Code)\n\n\trouter.NoMethod(func(c *Context) {\n\t\tc.String(http.StatusTeapot, \"responseText\")\n\t})\n\tw = PerformRequest(router, http.MethodGet, \"/path\")\n\tassert.Equal(t, \"responseText\", w.Body.String())\n\tassert.Equal(t, http.StatusTeapot, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":563,"symbol":"TestRouteNotAllowedEnabled2","kind":"function","lang":"go","code":"func TestRouteNotAllowedEnabled2(t *testing.T) {\n\trouter := New()\n\trouter.HandleMethodNotAllowed = true\n\t// add one methodTree to trees\n\trouter.addRoute(http.MethodPost, \"/\", HandlersChain{func(_ *Context) {}})\n\trouter.GET(\"/path2\", func(c *Context) {})\n\tw := PerformRequest(router, http.MethodPost, \"/path2\")\n\tassert.Equal(t, http.StatusMethodNotAllowed, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":573,"symbol":"TestRouteNotAllowedEnabled3","kind":"function","lang":"go","code":"func TestRouteNotAllowedEnabled3(t *testing.T) {\n\trouter := New()\n\trouter.HandleMethodNotAllowed = true\n\trouter.GET(\"/path\", func(c *Context) {})\n\trouter.POST(\"/path\", func(c *Context) {})\n\tw := PerformRequest(router, http.MethodPut, \"/path\")\n\tassert.Equal(t, http.StatusMethodNotAllowed, w.Code)\n\tallowed := w.Header().Get(\"Allow\")\n\tassert.Contains(t, allowed, http.MethodGet)\n\tassert.Contains(t, allowed, http.MethodPost)\n}"} {"repo":"gin","file":"routes_test.go","line":585,"symbol":"TestRouteNotAllowedDisabled","kind":"function","lang":"go","code":"func TestRouteNotAllowedDisabled(t *testing.T) {\n\trouter := New()\n\trouter.HandleMethodNotAllowed = false\n\trouter.POST(\"/path\", func(c *Context) {})\n\tw := PerformRequest(router, http.MethodGet, \"/path\")\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n\n\trouter.NoMethod(func(c *Context) {\n\t\tc.String(http.StatusTeapot, \"responseText\")\n\t})\n\tw = PerformRequest(router, http.MethodGet, \"/path\")\n\tassert.Equal(t, \"404 page not found\", w.Body.String())\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":600,"symbol":"TestRouterNotFoundWithRemoveExtraSlash","kind":"function","lang":"go","code":"func TestRouterNotFoundWithRemoveExtraSlash(t *testing.T) {\n\trouter := New()\n\trouter.RemoveExtraSlash = true\n\trouter.GET(\"/path\", func(c *Context) {})\n\trouter.GET(\"/\", func(c *Context) {})\n\n\ttestRoutes := []struct {\n\t\troute string\n\t\tcode int\n\t\tlocation string\n\t}{\n\t\t{\"/../path\", http.StatusOK, \"\"}, // CleanPath\n\t\t{\"/nope\", http.StatusNotFound, \"\"}, // NotFound\n\t}\n\tfor _, tr := range testRoutes {\n\t\tw := PerformRequest(router, http.MethodGet, tr.route)\n\t\tassert.Equal(t, tr.code, w.Code)\n\t\tif w.Code != http.StatusNotFound {\n\t\t\tassert.Equal(t, tr.location, w.Header().Get(\"Location\"))\n\t\t}\n\t}\n}"} {"repo":"gin","file":"routes_test.go","line":623,"symbol":"TestRouterNotFound","kind":"function","lang":"go","code":"func TestRouterNotFound(t *testing.T) {\n\trouter := New()\n\trouter.RedirectFixedPath = true\n\trouter.GET(\"/path\", func(c *Context) {})\n\trouter.GET(\"/dir/\", func(c *Context) {})\n\trouter.GET(\"/\", func(c *Context) {})\n\n\ttestRoutes := []struct {\n\t\troute string\n\t\tcode int\n\t\tlocation string\n\t}{\n\t\t{\"/path/\", http.StatusMovedPermanently, \"/path\"}, // TSR -/\n\t\t{\"/dir\", http.StatusMovedPermanently, \"/dir/\"}, // TSR +/\n\t\t{\"/PATH\", http.StatusMovedPermanently, \"/path\"}, // Fixed Case\n\t\t{\"/DIR/\", http.StatusMovedPermanently, \"/dir/\"}, // Fixed Case\n\t\t{\"/PATH/\", http.StatusMovedPermanently, \"/path\"}, // Fixed Case -/\n\t\t{\"/DIR\", http.StatusMovedPermanently, \"/dir/\"}, // Fixed Case +/\n\t\t{\"/../path\", http.StatusMovedPermanently, \"/path\"}, // Without CleanPath\n\t\t{\"/nope\", http.StatusNotFound, \"\"}, // NotFound\n\t}\n\tfor _, tr := range testRoutes {\n\t\tw := PerformRequest(router, http.MethodGet, tr.route)\n\t\tassert.Equal(t, tr.code, w.Code)\n\t\tif w.Code != http.StatusNotFound {\n\t\t\tassert.Equal(t, tr.location, w.Header().Get(\"Location\"))\n\t\t}\n\t}\n\n\t// Test custom not found handler\n\tvar notFound bool\n\trouter.NoRoute(func(c *Context) {\n\t\tc.AbortWithStatus(http.StatusNotFound"} {"repo":"gin","file":"routes_test.go","line":653,"symbol":"notFound","kind":"variable","lang":"go","doc":"Test custom not found handler","code":"notFound bool"} {"repo":"gin","file":"routes_test.go","line":690,"symbol":"TestRouterStaticFSNotFound","kind":"function","lang":"go","code":"func TestRouterStaticFSNotFound(t *testing.T) {\n\trouter := New()\n\trouter.StaticFS(\"/\", http.FileSystem(http.Dir(\"/thisreallydoesntexist/\")))\n\trouter.NoRoute(func(c *Context) {\n\t\tc.String(http.StatusNotFound, \"non existent\")\n\t})\n\n\tw := PerformRequest(router, http.MethodGet, \"/nonexistent\")\n\tassert.Equal(t, \"non existent\", w.Body.String())\n\n\tw = PerformRequest(router, http.MethodHead, \"/nonexistent\")\n\tassert.Equal(t, \"non existent\", w.Body.String())\n}"} {"repo":"gin","file":"routes_test.go","line":704,"symbol":"TestRouterStaticFSFileNotFound","kind":"function","lang":"go","code":"func TestRouterStaticFSFileNotFound(t *testing.T) {\n\trouter := New()\n\n\trouter.StaticFS(\"/\", http.FileSystem(http.Dir(\".\")))\n\n\tassert.NotPanics(t, func() {\n\t\tPerformRequest(router, http.MethodGet, \"/nonexistent\")\n\t})\n}"} {"repo":"gin","file":"routes_test.go","line":715,"symbol":"TestMiddlewareCalledOnceByRouterStaticFSNotFound","kind":"function","lang":"go","doc":"TestMiddlewareCalledOnceByRouterStaticFSNotFound reproduces the bug reported in issue #1805.","code":"func TestMiddlewareCalledOnceByRouterStaticFSNotFound(t *testing.T) {\n\trouter := New()\n\n\t// Middleware must be called just only once by per request.\n\tmiddlewareCalledNum := 0\n\trouter.Use(func(c *Context) {\n\t\tmiddlewareCalledNum++\n\t})\n\n\trouter.StaticFS(\"/\", http.FileSystem(http.Dir(\"/thisreallydoesntexist/\")))\n\n\t// First access\n\tPerformRequest(router, http.MethodGet, \"/nonexistent\")\n\tassert.Equal(t, 1, middlewareCalledNum)\n\n\t// Second access\n\tPerformRequest(router, http.MethodHead, \"/nonexistent\")\n\tassert.Equal(t, 2, middlewareCalledNum)\n}"} {"repo":"gin","file":"routes_test.go","line":735,"symbol":"TestRouteRawPath","kind":"function","lang":"go","code":"func TestRouteRawPath(t *testing.T) {\n\troute := New()\n\troute.UseRawPath = true\n\n\troute.POST(\"/project/:name/build/:num\", func(c *Context) {\n\t\tname := c.Params.ByName(\"name\")\n\t\tnum := c.Params.ByName(\"num\")\n\n\t\tassert.Equal(t, name, c.Param(\"name\"))\n\t\tassert.Equal(t, num, c.Param(\"num\"))\n\n\t\tassert.Equal(t, \"Some/Other/Project\", name)\n\t\tassert.Equal(t, \"222\", num)\n\t})\n\n\tw := PerformRequest(route, http.MethodPost, \"/project/Some%2FOther%2FProject/build/222\")\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":754,"symbol":"TestRouteRawPathNoUnescape","kind":"function","lang":"go","code":"func TestRouteRawPathNoUnescape(t *testing.T) {\n\troute := New()\n\troute.UseRawPath = true\n\troute.UnescapePathValues = false\n\n\troute.POST(\"/project/:name/build/:num\", func(c *Context) {\n\t\tname := c.Params.ByName(\"name\")\n\t\tnum := c.Params.ByName(\"num\")\n\n\t\tassert.Equal(t, name, c.Param(\"name\"))\n\t\tassert.Equal(t, num, c.Param(\"num\"))\n\n\t\tassert.Equal(t, \"Some%2FOther%2FProject\", name)\n\t\tassert.Equal(t, \"333\", num)\n\t})\n\n\tw := PerformRequest(route, http.MethodPost, \"/project/Some%2FOther%2FProject/build/333\")\n\tassert.Equal(t, http.StatusOK, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":774,"symbol":"TestRouteServeErrorWithWriteHeader","kind":"function","lang":"go","code":"func TestRouteServeErrorWithWriteHeader(t *testing.T) {\n\troute := New()\n\troute.Use(func(c *Context) {\n\t\tc.Status(http.StatusMisdirectedRequest)\n\t\tc.Next()\n\t})\n\n\tw := PerformRequest(route, http.MethodGet, \"/NotFound\")\n\tassert.Equal(t, http.StatusMisdirectedRequest, w.Code)\n\tassert.Equal(t, 0, w.Body.Len())\n}"} {"repo":"gin","file":"routes_test.go","line":786,"symbol":"TestRouteContextHoldsFullPath","kind":"function","lang":"go","code":"func TestRouteContextHoldsFullPath(t *testing.T) {\n\trouter := New()\n\n\t// Test routes\n\troutes := []string{\n\t\t\"/simple\",\n\t\t\"/project/:name\",\n\t\t\"/\",\n\t\t\"/news/home\",\n\t\t\"/news\",\n\t\t\"/simple-two/one\",\n\t\t\"/simple-two/one-two\",\n\t\t\"/project/:name/build/*params\",\n\t\t\"/project/:name/bui\",\n\t\t\"/user/:id/status\",\n\t\t\"/user/:id\",\n\t\t\"/user/:id/profile\",\n\t}\n\n\tfor _, route := range routes {\n\t\tactualRoute := route\n\t\trouter.GET(route, func(c *Context) {\n\t\t\t// For each defined route context should contain its full path\n\t\t\tassert.Equal(t, actualRoute, c.FullPath())\n\t\t\tc.AbortWithStatus(http.StatusOK)\n\t\t})\n\t}\n\n\tfor _, route := range routes {\n\t\tw := PerformRequest(router, http.MethodGet, route)\n\t\tassert.Equal(t, http.StatusOK, w.Code)\n\t}\n\n\t// Test not found\n\trouter.Use(func(c *Context) {\n\t\t// For not found routes full path is empty\n\t\tassert.Empty(t, c.FullPath())\n\t})\n\n\tw := PerformRequest(router, http.MethodGet, \"/not-found\")\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":829,"symbol":"TestEngineHandleMethodNotAllowedCornerCase","kind":"function","lang":"go","code":"func TestEngineHandleMethodNotAllowedCornerCase(t *testing.T) {\n\tr := New()\n\tr.HandleMethodNotAllowed = true\n\n\tbase := r.Group(\"base\")\n\tbase.GET(\"/metrics\", handlerTest1)\n\n\tv1 := base.Group(\"v1\")\n\n\tv1.GET(\"/:id/devices\", handlerTest1)\n\tv1.GET(\"/user/:id/groups\", handlerTest1)\n\n\tv1.GET(\"/orgs/:id\", handlerTest1)\n\tv1.DELETE(\"/orgs/:id\", handlerTest1)\n\n\tw := PerformRequest(r, http.MethodGet, \"/base/v1/user/groups\")\n\tassert.Equal(t, http.StatusNotFound, w.Code)\n}"} {"repo":"gin","file":"routes_test.go","line":854,"symbol":"TestIssue4818_skippedNodesOverflow_Panic","kind":"function","lang":"go","doc":"TestIssue4818_skippedNodesOverflow_Panic reproduces the panic from issue #4818: with HandleMethodNotAllowed enabled, getValue is called once per method tree reusing the same c.skippedNodes stack without resetting it, so residue accumulates until the reslice exceeds the capacity (engine.maxSections). The request must not panic and must fall through to the normal 404 path (the path genuinely matches no route, so 405 is not applicable here).","code":"func TestIssue4818_skippedNodesOverflow_Panic(t *testing.T) {\n\trouter := New()\n\trouter.HandleMethodNotAllowed = true\n\n\th := func(c *Context) {}\n\trouter.OPTIONS(\"/:p0/:p1/a/:p2\", h)\n\trouter.GET(\"/:p0/:p1/a/:p2\", h)\n\trouter.PATCH(\"/b/:p0/:p1/c\", h)\n\trouter.DELETE(\"/b/:p0/:p1/d/:p3\", h)\n\trouter.GET(\"/b/:p0/:p1/e/f\", h)\n\trouter.POST(\"/b/:p0/:p1/g/:p4/h\", h)\n\trouter.OPTIONS(\"/b/:p0/:p1/g/:p4/h\", h)\n\trouter.DELETE(\"/b/cache\", h)\n\trouter.GET(\"/b/clients/:p1/g\", h)\n\trouter.POST(\"/b/clients/:p1/g\", h)\n\trouter.PATCH(\"/b/clients/:p1/g/:p4\", h)\n\trouter.OPTIONS(\"/b/clients/:p1/g/:p4\", h)\n\n\treq := httptest.NewRequest(http.MethodPost, \"/b/clients/42\", nil)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\n\t// Must not panic; path matches no route, so 404 is the correct outcome.\n\tif w.Code != http.StatusNotFound {\n\t\tt.Fatalf(\"expected 404, got %d (a panic would have aborted the test)\", w.Code)\n\t}\n}"} {"repo":"gin","file":"routes_test.go","line":885,"symbol":"TestIssue4818_MethodNotAllowedStillWorks","kind":"function","lang":"go","doc":"TestIssue4818_MethodNotAllowedStillWorks verifies the HandleMethodNotAllowed loop still produces a correct 405 with an Allow header after the fix, i.e. the reset does not break the loop across multiple method trees.","code":"func TestIssue4818_MethodNotAllowedStillWorks(t *testing.T) {\n\trouter := New()\n\trouter.HandleMethodNotAllowed = true\n\n\th := func(c *Context) {}\n\trouter.OPTIONS(\"/:p0/:p1/a/:p2\", h)\n\trouter.GET(\"/:p0/:p1/a/:p2\", h)\n\trouter.PATCH(\"/b/:p0/:p1/c\", h)\n\trouter.DELETE(\"/b/:p0/:p1/d/:p3\", h)\n\trouter.GET(\"/b/:p0/:p1/e/f\", h)\n\trouter.POST(\"/b/:p0/:p1/g/:p4/h\", h)\n\trouter.OPTIONS(\"/b/:p0/:p1/g/:p4/h\", h)\n\trouter.DELETE(\"/b/cache\", h)\n\trouter.GET(\"/b/clients/:p1/g\", h)\n\trouter.POST(\"/b/clients/:p1/g\", h)\n\trouter.PATCH(\"/b/clients/:p1/g/:p4\", h)\n\trouter.OPTIONS(\"/b/clients/:p1/g/:p4\", h)\n\n\t// PATCH /b/clients/42/g is registered under GET but not under PATCH\n\t// -> HandleMethodNotAllowed should yield 405 with an Allow header.\n\treq := httptest.NewRequest(http.MethodPatch, \"/b/clients/42/g\", nil)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\n\tif w.Code != http.StatusMethodNotAllowed {\n\t\tt.Fatalf(\"expected 405, got %d\", w.Code)\n\t}\n\tallow := w.Header().Get(\"Allow\")\n\tif allow == \"\" {\n\t\tt.Fatal(\"expected Allow header to be set for 405\")\n\t}\n}"} {"repo":"gin","file":"routes_test.go","line":920,"symbol":"TestIssue4818_MethodNotAllowedManyTrees","kind":"function","lang":"go","doc":"TestIssue4818_MethodNotAllowedManyTrees stresses the loop across many method trees to make sure the skipped-nodes accumulator can never overflow.","code":"func TestIssue4818_MethodNotAllowedManyTrees(t *testing.T) {\n\trouter := New()\n\trouter.HandleMethodNotAllowed = true\n\n\th := func(c *Context) {}\n\tfor _, m := range []string{\n\t\thttp.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete,\n\t\thttp.MethodPatch, http.MethodOptions, http.MethodHead, http.MethodConnect,\n\t\thttp.MethodTrace,\n\t} {\n\t\trouter.Handle(m, \"/:p0/:p1/a/:p2\", h)\n\t\trouter.Handle(m, \"/s/:p0/:p1/:p2/:p3/:p4/:p5/d\", h)\n\t}\n\t// GET route so that a POST to a GET-only path yields 405\n\trouter.GET(\"/only-get\", h)\n\n\treq := httptest.NewRequest(http.MethodPost, \"/only-get\", nil)\n\tw := httptest.NewRecorder()\n\trouter.ServeHTTP(w, req)\n\n\tif w.Code != http.StatusMethodNotAllowed {\n\t\tt.Fatalf(\"expected 405, got %d\", w.Code)\n\t}\n}"} {"repo":"gin","file":"test_helpers.go","line":17,"symbol":"CreateTestContext","kind":"function","lang":"go","doc":"CreateTestContext returns a fresh Engine and a Context associated with it. This is useful for tests that need to set up a new Gin engine instance along with a context, for example, to test middleware that doesn't depend on specific routes. The ResponseWriter `w` is used to initialize the context's writer.","code":"func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {\n\tr = New()\n\tc = r.allocateContext(0)\n\tc.reset()\n\tc.writermem.reset(w)\n\treturn\n}"} {"repo":"gin","file":"test_helpers.go","line":30,"symbol":"CreateTestContextOnly","kind":"function","lang":"go","doc":"CreateTestContextOnly returns a fresh Context associated with the provided Engine `r`. This is useful for tests that operate on an existing, possibly pre-configured, Gin engine instance and need a new context for it. The ResponseWriter `w` is used to initialize the context's writer. The context is allocated with the `maxParams` setting from the provided engine.","code":"func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) {\n\tc = r.allocateContext(r.maxParams)\n\tc.reset()\n\tc.writermem.reset(w)\n\treturn\n}"} {"repo":"gin","file":"test_helpers.go","line":39,"symbol":"waitForServerReady","kind":"function","lang":"go","doc":"waitForServerReady waits for a server to be ready by making HTTP requests with exponential backoff. This is more reliable than time.Sleep() for testing.","code":"func waitForServerReady(url string, maxAttempts int) error {\n\tclient := &http.Client{\n\t\tTimeout: 100 * time.Millisecond,\n\t}\n\n\tfor i := 0; i < maxAttempts; i++ {\n\t\tresp, err := client.Get(url)\n\t\tif err == nil {\n\t\t\tresp.Body.Close()\n\t\t\treturn nil\n\t\t}\n\n\t\t// Exponential backoff: 10ms, 20ms, 40ms, 80ms, 160ms...\n\t\tbackoff := min(time.Duration(10*(1< protoexample.Test.OptionalGroup\n\t1, // [1:1] is the sub-list for method output_type\n\t1, // [1:1] is the sub-list for method input_type\n\t1, // [1:1] is the sub-list for extension type_name\n\t1, // [1:1] is the sub-list for extension extendee\n\t0, // [0:1] is the sub-list for field type_name\n}"} {"repo":"gin","file":"testdata/protoexample/test.pb.go","line":248,"symbol":"init","kind":"function","lang":"go","code":"func init() { file_test_proto_init() }"} {"repo":"gin","file":"testdata/protoexample/test.pb.go","line":249,"symbol":"file_test_proto_init","kind":"function","lang":"go","code":"func file_test_proto_init() {\n\tif File_test_proto != nil {\n\t\treturn\n\t}\n\tif !protoimpl.UnsafeEnabled {\n\t\tfile_test_proto_msgTypes[0].Exporter = func(v any, i int) any {\n\t\t\tswitch v := v.(*Test); i {\n\t\t\tcase 0:\n\t\t\t\treturn &v.state\n\t\t\tcase 1:\n\t\t\t\treturn &v.sizeCache\n\t\t\tcase 2:\n\t\t\t\treturn &v.unknownFields\n\t\t\tdefault:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\tfile_test_proto_msgTypes[1].Exporter = func(v any, i int) any {\n\t\t\tswitch v := v.(*Test_OptionalGroup); i {\n\t\t\tcase 0:\n\t\t\t\treturn &v.state\n\t\t\tcase 1:\n\t\t\t\treturn &v.sizeCache\n\t\t\tcase 2:\n\t\t\t\treturn &v.unknownFields\n\t\t\tdefault:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\ttype x struct{}\n\tout := protoimpl.TypeBuilder{\n\t\tFile: protoimpl.DescBuilder{\n\t\t\tGoPackagePath: reflect.TypeOf(x{}).PkgPath(),\n\t\t\tRawDescriptor: file_test_proto_rawDesc,\n\t\t\tNumEnums: 1,\n\t\t\tNumMessages: 2,\n\t\t\tNumExtensions: 0,\n\t\t\tNumServices: 0,\n\t\t},\n\t\tGoTypes: file_test_proto_goTypes,\n\t\tDependencyIndexes: file_test_proto_depIdxs,\n\t\tEnumInfos: file_test_proto_enumTypes,\n\t\tMessageInfos: file_test_proto_msgTypes,\n\t}.Build()\n\tFile_test_proto = out.File\n\tfile_test_proto_rawDesc = nil\n\tfile_test_proto_goTypes = nil\n\tfile_test_proto_depIdxs = nil\n}"} {"repo":"gin","file":"testdata/protoexample/test.pb.go","line":279,"symbol":"x","kind":"type","lang":"go","code":"type x struct{}"} {"repo":"gin","file":"testdata/protoexample/test.proto","line":3,"symbol":"FOO","kind":"type","lang":"proto","code":"enum FOO {X=17;}"} {"repo":"gin","file":"testdata/protoexample/test.proto","line":5,"symbol":"Test","kind":"type","lang":"proto","code":"message Test {\n required string label = 1;\n optional int32 type = 2[default=77];\n repeated int64 reps = 3;\n optional group OptionalGroup = 4{\n required string RequiredField = 5;\n }"} {"repo":"gin","file":"testdata/protoexample/test.proto","line":6,"symbol":"label","kind":"field","lang":"proto","code":"required string label = 1;"} {"repo":"gin","file":"testdata/protoexample/test.proto","line":7,"symbol":"type","kind":"field","lang":"proto","code":"optional int32 type = 2[default=77];"} {"repo":"gin","file":"testdata/protoexample/test.proto","line":8,"symbol":"reps","kind":"field","lang":"proto","code":"repeated int64 reps = 3;"} {"repo":"gin","file":"testdata/protoexample/test.proto","line":10,"symbol":"RequiredField","kind":"field","lang":"proto","code":"required string RequiredField = 5;"} {"repo":"gin","file":"tree.go","line":17,"symbol":"Param","kind":"type","lang":"go","doc":"Param is a single URL parameter, consisting of a key and a value.","code":"type Param struct {\n\tKey string\n\tValue string\n}"} {"repo":"gin","file":"tree.go","line":25,"symbol":"Params","kind":"type","lang":"go","doc":"Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.","code":"type Params []Param"} {"repo":"gin","file":"tree.go","line":29,"symbol":"Get","kind":"method","lang":"go","doc":"Get returns the value of the first Param which key matches the given name and a boolean true. If no matching Param is found, an empty string is returned and a boolean false .","code":"func (ps Params) Get(name string) (string, bool) {\n\tfor _, entry := range ps {\n\t\tif entry.Key == name {\n\t\t\treturn entry.Value, true\n\t\t}\n\t}\n\treturn \"\", false\n}"} {"repo":"gin","file":"tree.go","line":40,"symbol":"ByName","kind":"method","lang":"go","doc":"ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.","code":"func (ps Params) ByName(name string) (va string) {\n\tva, _ = ps.Get(name)\n\treturn\n}"} {"repo":"gin","file":"tree.go","line":45,"symbol":"methodTree","kind":"type","lang":"go","code":"type methodTree struct {\n\tmethod string\n\troot *node\n}"} {"repo":"gin","file":"tree.go","line":50,"symbol":"methodTrees","kind":"type","lang":"go","code":"type methodTrees []methodTree"} {"repo":"gin","file":"tree.go","line":52,"symbol":"get","kind":"method","lang":"go","code":"func (trees methodTrees) get(method string) *node {\n\tfor _, tree := range trees {\n\t\tif tree.method == method {\n\t\t\treturn tree.root\n\t\t}\n\t}\n\treturn nil\n}"} {"repo":"gin","file":"tree.go","line":61,"symbol":"longestCommonPrefix","kind":"function","lang":"go","code":"func longestCommonPrefix(a, b string) int {\n\ti := 0\n\tmax_ := min(len(a), len(b))\n\tfor i < max_ && a[i] == b[i] {\n\t\ti++\n\t}\n\treturn i\n}"} {"repo":"gin","file":"tree.go","line":71,"symbol":"addChild","kind":"method","lang":"go","doc":"addChild will add a child node, keeping wildcardChild at the end","code":"func (n *node) addChild(child *node) {\n\tif n.wildChild && len(n.children) > 0 {\n\t\twildcardChild := n.children[len(n.children)-1]\n\t\tn.children = append(n.children[:len(n.children)-1], child, wildcardChild)\n\t} else {\n\t\tn.children = append(n.children, child)\n\t}\n}"} {"repo":"gin","file":"tree.go","line":80,"symbol":"countParams","kind":"function","lang":"go","code":"func countParams(path string) uint16 {\n\tcolons := strings.Count(path, \":\")\n\tstars := strings.Count(path, \"*\")\n\treturn safeUint16(colons + stars)\n}"} {"repo":"gin","file":"tree.go","line":86,"symbol":"countSections","kind":"function","lang":"go","code":"func countSections(path string) uint16 {\n\treturn safeUint16(strings.Count(path, \"/\"))\n}"} {"repo":"gin","file":"tree.go","line":90,"symbol":"nodeType","kind":"type","lang":"go","code":"type nodeType uint8"} {"repo":"gin","file":"tree.go","line":93,"symbol":"static","kind":"constant","lang":"go","code":"static nodeType = iota"} {"repo":"gin","file":"tree.go","line":94,"symbol":"root","kind":"constant","lang":"go","code":"root"} {"repo":"gin","file":"tree.go","line":95,"symbol":"param","kind":"constant","lang":"go","code":"param"} {"repo":"gin","file":"tree.go","line":96,"symbol":"catchAll","kind":"constant","lang":"go","code":"catchAll"} {"repo":"gin","file":"tree.go","line":99,"symbol":"node","kind":"type","lang":"go","code":"type node struct {\n\tpath string\n\tindices string\n\twildChild bool\n\tnType nodeType\n\tpriority uint32\n\tchildren []*node // child nodes, at most 1 :param style node at the end of the array\n\thandlers HandlersChain\n\tfullPath string\n}"} {"repo":"gin","file":"tree.go","line":111,"symbol":"incrementChildPrio","kind":"method","lang":"go","doc":"incrementChildPrio increments the priority of the given child and reorders it if necessary.","code":"func (n *node) incrementChildPrio(pos int) int {\n\tcs := n.children\n\tcs[pos].priority++\n\tprio := cs[pos].priority\n\n\t// Adjust position (move to front)\n\tnewPos := pos\n\tfor ; newPos > 0 && cs[newPos-1].priority < prio; newPos-- {\n\t\t// Swap node positions\n\t\tcs[newPos-1], cs[newPos] = cs[newPos], cs[newPos-1]\n\t}\n\n\t// Build new index char string\n\tif newPos != pos {\n\t\tn.indices = n.indices[:newPos] + // Unchanged prefix, might be empty\n\t\t\tn.indices[pos:pos+1] + // The index char we move\n\t\t\tn.indices[newPos:pos] + n.indices[pos+1:] // Rest without char at 'pos'\n\t}\n\n\treturn newPos\n}"} {"repo":"gin","file":"tree.go","line":135,"symbol":"addRoute","kind":"method","lang":"go","doc":"addRoute adds a node with the given handle to the path. Not concurrency-safe!","code":"func (n *node) addRoute(path string, handlers HandlersChain) {\n\tfullPath := path\n\tn.priority++\n\n\t// Empty tree\n\tif len(n.path) == 0 && len(n.children) == 0 {\n\t\tn.insertChild(path, fullPath, handlers)\n\t\tn.nType = root\n\t\treturn\n\t}\n\n\tparentFullPathIndex := 0\n\nwalk:\n\tfor {\n\t\t// Find the longest common prefix.\n\t\t// This also implies that the common prefix contains no ':' or '*'\n\t\t// since the existing key can't contain those chars.\n\t\ti := longestCommonPrefix(path, n.path)\n\n\t\t// Split edge\n\t\tif i < len(n.path) {\n\t\t\tchild := node{\n\t\t\t\tpath: n.path[i:],\n\t\t\t\twildChild: n.wildChild,\n\t\t\t\tnType: static,\n\t\t\t\tindices: n.indices,\n\t\t\t\tchildren: n.children,\n\t\t\t\thandlers: n.handlers,\n\t\t\t\tpriority: n.priority - 1,\n\t\t\t\tfullPath: n.fullPath,\n\t\t\t}\n\n\t\t\tn.children = []*node{&child}\n\t\t\t// []byte for proper unicode char conversion, see #65\n\t\t\tn.indices = bytesconv.BytesToString([]byte{n.path[i]})\n\t\t\tn.path = path[:i]\n\t\t\tn.handlers = nil\n\t\t\tn.wildChild = false\n\t\t\tn.fullPath = fullPath[:parentFullPathIndex+i]\n\t\t}\n\n\t\t// Make new node a child of this node\n\t\tif i < len(path) {\n\t\t\tpath = path[i:]\n\t\t\tc := path[0]\n\n\t\t\t// '/' after param\n\t\t\tif n.nType == param && c == '/' && len(n.children) == 1 {\n\t\t\t"} {"repo":"gin","file":"tree.go","line":253,"symbol":"findWildcard","kind":"function","lang":"go","doc":"Search for a wildcard segment and check the name for invalid characters. Returns -1 as index, if no wildcard was found.","code":"func findWildcard(path string) (wildcard string, i int, valid bool) {\n\t// Find start\n\tescapeColon := false\n\tfor start, c := range []byte(path) {\n\t\tif escapeColon {\n\t\t\tescapeColon = false\n\t\t\tif c == ':' {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpanic(\"invalid escape string in path '\" + path + \"'\")\n\t\t}\n\t\tif c == '\\\\' {\n\t\t\tescapeColon = true\n\t\t\tcontinue\n\t\t}\n\t\t// A wildcard starts with ':' (param) or '*' (catch-all)\n\t\tif c != ':' && c != '*' {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Find end and check for invalid characters\n\t\tvalid = true\n\t\tfor end, c := range []byte(path[start+1:]) {\n\t\t\tswitch c {\n\t\t\tcase '/':\n\t\t\t\treturn path[start : start+1+end], start, valid\n\t\t\tcase ':', '*':\n\t\t\t\tvalid = false\n\t\t\t}\n\t\t}\n\t\treturn path[start:], start, valid\n\t}\n\treturn \"\", -1, false\n}"} {"repo":"gin","file":"tree.go","line":288,"symbol":"insertChild","kind":"method","lang":"go","code":"func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) {\n\tfor {\n\t\t// Find prefix until first wildcard\n\t\twildcard, i, valid := findWildcard(path)\n\t\tif i < 0 { // No wildcard found\n\t\t\tbreak\n\t\t}\n\n\t\t// The wildcard name must only contain one ':' or '*' character\n\t\tif !valid {\n\t\t\tpanic(\"only one wildcard per path segment is allowed, has: '\" +\n\t\t\t\twildcard + \"' in path '\" + fullPath + \"'\")\n\t\t}\n\n\t\t// check if the wildcard has a name\n\t\tif len(wildcard) < 2 {\n\t\t\tpanic(\"wildcards must be named with a non-empty name in path '\" + fullPath + \"'\")\n\t\t}\n\n\t\tif wildcard[0] == ':' { // param\n\t\t\tif i > 0 {\n\t\t\t\t// Insert prefix before the current wildcard\n\t\t\t\tn.path = path[:i]\n\t\t\t\tpath = path[i:]\n\t\t\t}\n\n\t\t\tchild := &node{\n\t\t\t\tnType: param,\n\t\t\t\tpath: wildcard,\n\t\t\t\tfullPath: fullPath,\n\t\t\t}\n\t\t\tn.addChild(child)\n\t\t\tn.wildChild = true\n\t\t\tn = child\n\t\t\tn.priority++\n\n\t\t\t// if the path doesn't end with the wildcard, then there\n\t\t\t// will be another subpath starting with '/'\n\t\t\tif len(wildcard) < len(path) {\n\t\t\t\tpath = path[len(wildcard):]\n\n\t\t\t\tchild := &node{\n\t\t\t\t\tpriority: 1,\n\t\t\t\t\tfullPath: fullPath,\n\t\t\t\t}\n\t\t\t\tn.addChild(child)\n\t\t\t\tn = child\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Otherwise we"} {"repo":"gin","file":"tree.go","line":400,"symbol":"nodeValue","kind":"type","lang":"go","doc":"nodeValue holds return values of (*Node).getValue method","code":"type nodeValue struct {\n\thandlers HandlersChain\n\tparams *Params\n\ttsr bool\n\tfullPath string\n}"} {"repo":"gin","file":"tree.go","line":407,"symbol":"skippedNode","kind":"type","lang":"go","code":"type skippedNode struct {\n\tpath string\n\tnode *node\n\tparamsCount int16\n}"} {"repo":"gin","file":"tree.go","line":418,"symbol":"getValue","kind":"method","lang":"go","doc":"Returns the handle registered with the given path (key). The values of wildcards are saved to a map. If no handle can be found, a TSR (trailing slash redirect) recommendation is made if a handle exists with an extra (without the) trailing slash for the given path.","code":"func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) {\n\tvar globalParamsCount int16\n\n\t// Reset the skipped-nodes stack on entry. getValue is called once per\n\t// method tree (e.g. in the HandleMethodNotAllowed loop) reusing the same\n\t// pooled Context stack, and the walk below grows it via a raw reslice that\n\t// cannot exceed engine.maxSections. Without this reset the residue from a\n\t// previous tree leaks into the next call and can panic with \"slice bounds\n\t// out of range\" once the accumulated length passes the capacity.\n\t*skippedNodes = (*skippedNodes)[:0]\n\nwalk: // Outer loop for walking the tree\n\tfor {\n\t\tprefix := n.path\n\t\tif len(path) > len(prefix) {\n\t\t\tif path[:len(prefix)] == prefix {\n\t\t\t\tpath = path[len(prefix):]\n\n\t\t\t\t// Try all the non-wildcard children first by matching the indices\n\t\t\t\tidxc := path[0]\n\t\t\t\tfor i, c := range []byte(n.indices) {\n\t\t\t\t\tif c == idxc {\n\t\t\t\t\t\t// strings.HasPrefix(n.children[len(n.children)-1].path, \":\") == n.wildChild\n\t\t\t\t\t\tif n.wildChild {\n\t\t\t\t\t\t\tindex := len(*skippedNodes)\n\t\t\t\t\t\t\t*skippedNodes = (*skippedNodes)[:index+1]\n\t\t\t\t\t\t\t(*skippedNodes)[index] = skippedNode{\n\t\t\t\t\t\t\t\tpath: pre"} {"repo":"gin","file":"tree.go","line":419,"symbol":"globalParamsCount","kind":"variable","lang":"go","code":"globalParamsCount int16"} {"repo":"gin","file":"tree.go","line":679,"symbol":"findCaseInsensitivePath","kind":"method","lang":"go","doc":"Makes a case-insensitive lookup of the given path and tries to find a handler. It can optionally also fix trailing slashes. It returns the case-corrected path and a bool indicating whether the lookup was successful.","code":"func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) {\n\tconst stackBufSize = 128\n\n\tbuf := make([]byte, 0, max(stackBufSize, len(path)+1))\n\n\tciPath := n.findCaseInsensitivePathRec(\n\t\tpath,\n\t\tbuf, // Preallocate enough memory for new path\n\t\t[4]byte{}, // Empty rune buffer\n\t\tfixTrailingSlash,\n\t)\n\n\treturn ciPath, ciPath != nil\n}"} {"repo":"gin","file":"tree.go","line":680,"symbol":"stackBufSize","kind":"constant","lang":"go","code":"stackBufSize = 128"} {"repo":"gin","file":"tree.go","line":695,"symbol":"shiftNRuneBytes","kind":"function","lang":"go","doc":"shiftNRuneBytes shifts bytes in the array n positions to the left.","code":"func shiftNRuneBytes(rb [4]byte, n int) [4]byte {\n\tswitch n {\n\tcase 0:\n\t\treturn rb\n\tcase 1:\n\t\treturn [4]byte{rb[1], rb[2], rb[3], 0}\n\tcase 2:\n\t\treturn [4]byte{rb[2], rb[3]}\n\tcase 3:\n\t\treturn [4]byte{rb[3]}\n\tdefault:\n\t\treturn [4]byte{}\n\t}\n}"} {"repo":"gin","file":"tree.go","line":711,"symbol":"findCaseInsensitivePathRec","kind":"method","lang":"go","doc":"findCaseInsensitivePathRec recursively performs a case-insensitive path lookup.","code":"func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte {\n\tnpLen := len(n.path)\n\nwalk: // Outer loop for walking the tree\n\tfor len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) {\n\t\t// Add common prefix to result\n\t\toldPath := path\n\t\tpath = path[npLen:]\n\t\tciPath = append(ciPath, n.path...)\n\n\t\tif len(path) == 0 {\n\t\t\t// We should have reached the node containing the handle.\n\t\t\t// Check if this node has a handle registered.\n\t\t\tif n.handlers != nil {\n\t\t\t\treturn ciPath\n\t\t\t}\n\n\t\t\t// No handle found.\n\t\t\t// Try to fix the path by adding a trailing slash\n\t\t\tif fixTrailingSlash {\n\t\t\t\tfor i, c := range []byte(n.indices) {\n\t\t\t\t\tif c == '/' {\n\t\t\t\t\t\tn = n.children[i]\n\t\t\t\t\t\tif (len(n.path) == 1 && n.handlers != nil) ||\n\t\t\t\t\t\t\t(n.nType == catchAll && n.children[0].handlers != nil) {\n\t\t\t\t\t\t\treturn append(ciPath, '/')\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t// If this node does not have a wildcard (param or catchAll) child,\n\t\t// we can just look up the next child node and continue to walk down\n\t\t// the tree\n\t\tif !n.wildChild {\n\t\t\t// Skip rune bytes already processed\n\t\t\trb = shiftNRuneBytes(r"} {"repo":"gin","file":"tree.go","line":765,"symbol":"rv","kind":"variable","lang":"go","doc":"Process a new rune","code":"rv rune"} {"repo":"gin","file":"tree.go","line":770,"symbol":"off","kind":"variable","lang":"go","doc":"Find rune start. Runes are up to 4 byte long, -4 would definitely be another rune.","code":"off int"} {"repo":"gin","file":"tree.go","line":849,"symbol":"rv","kind":"variable","lang":"go","code":"rv rune"} {"repo":"gin","file":"tree.go","line":850,"symbol":"off","kind":"variable","lang":"go","code":"off int"} {"repo":"gin","file":"tree_test.go","line":16,"symbol":"fakeHandlerValue","kind":"variable","lang":"go","doc":"Used as a workaround since we can't compare functions or their addresses","code":"fakeHandlerValue string"} {"repo":"gin","file":"tree_test.go","line":18,"symbol":"fakeHandler","kind":"function","lang":"go","code":"func fakeHandler(val string) HandlersChain {\n\treturn HandlersChain{func(c *Context) {\n\t\tfakeHandlerValue = val\n\t}}\n}"} {"repo":"gin","file":"tree_test.go","line":24,"symbol":"testRequests","kind":"type","lang":"go","code":"type testRequests []struct {\n\tpath string\n\tnilHandler bool\n\troute string\n\tps Params\n}"} {"repo":"gin","file":"tree_test.go","line":31,"symbol":"getParams","kind":"function","lang":"go","code":"func getParams() *Params {\n\tps := make(Params, 0, 20)\n\treturn &ps\n}"} {"repo":"gin","file":"tree_test.go","line":36,"symbol":"getSkippedNodes","kind":"function","lang":"go","code":"func getSkippedNodes() *[]skippedNode {\n\tps := make([]skippedNode, 0, 20)\n\treturn &ps\n}"} {"repo":"gin","file":"tree_test.go","line":41,"symbol":"checkRequests","kind":"function","lang":"go","code":"func checkRequests(t *testing.T, tree *node, requests testRequests, unescapes ...bool) {\n\tunescape := false\n\tif len(unescapes) >= 1 {\n\t\tunescape = unescapes[0]\n\t}\n\n\tfor _, request := range requests {\n\t\tvalue := tree.getValue(request.path, getParams(), getSkippedNodes(), unescape)\n\n\t\tif value.handlers == nil {\n\t\t\tif !request.nilHandler {\n\t\t\t\tt.Errorf(\"handle mismatch for route '%s': Expected non-nil handle\", request.path)\n\t\t\t}\n\t\t} else if request.nilHandler {\n\t\t\tt.Errorf(\"handle mismatch for route '%s': Expected nil handle\", request.path)\n\t\t} else {\n\t\t\tvalue.handlers[0](nil)\n\t\t\tif fakeHandlerValue != request.route {\n\t\t\t\tt.Errorf(\"handle mismatch for route '%s': Wrong handle (%s != %s)\", request.path, fakeHandlerValue, request.route)\n\t\t\t}\n\t\t}\n\n\t\tif value.params != nil {\n\t\t\tif !reflect.DeepEqual(*value.params, request.ps) {\n\t\t\t\tt.Errorf(\"Params mismatch for route '%s'\", request.path)\n\t\t\t}\n\t\t}\n\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":72,"symbol":"checkPriorities","kind":"function","lang":"go","code":"func checkPriorities(t *testing.T, n *node) uint32 {\n\tvar prio uint32\n\tfor i := range n.children {\n\t\tprio += checkPriorities(t, n.children[i])\n\t}\n\n\tif n.handlers != nil {\n\t\tprio++\n\t}\n\n\tif n.priority != prio {\n\t\tt.Errorf(\n\t\t\t\"priority mismatch for node '%s': is %d, should be %d\",\n\t\t\tn.path, n.priority, prio,\n\t\t)\n\t}\n\n\treturn prio\n}"} {"repo":"gin","file":"tree_test.go","line":73,"symbol":"prio","kind":"variable","lang":"go","code":"prio uint32"} {"repo":"gin","file":"tree_test.go","line":92,"symbol":"TestCountParams","kind":"function","lang":"go","code":"func TestCountParams(t *testing.T) {\n\tif countParams(\"/path/:param1/static/*catch-all\") != 2 {\n\t\tt.Fail()\n\t}\n\tif countParams(strings.Repeat(\"/:param\", 256)) != 256 {\n\t\tt.Fail()\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":101,"symbol":"TestTreeAddAndGet","kind":"function","lang":"go","code":"func TestTreeAddAndGet(t *testing.T) {\n\ttree := &node{}\n\n\troutes := [...]string{\n\t\t\"/hi\",\n\t\t\"/contact\",\n\t\t\"/co\",\n\t\t\"/c\",\n\t\t\"/a\",\n\t\t\"/ab\",\n\t\t\"/doc/\",\n\t\t\"/doc/go_faq.html\",\n\t\t\"/doc/go1.html\",\n\t\t\"/α\",\n\t\t\"/β\",\n\t}\n\tfor _, route := range routes {\n\t\ttree.addRoute(route, fakeHandler(route))\n\t}\n\n\tcheckRequests(t, tree, testRequests{\n\t\t{\"/a\", false, \"/a\", nil},\n\t\t{\"/\", true, \"\", nil},\n\t\t{\"/hi\", false, \"/hi\", nil},\n\t\t{\"/contact\", false, \"/contact\", nil},\n\t\t{\"/co\", false, \"/co\", nil},\n\t\t{\"/con\", true, \"\", nil}, // key mismatch\n\t\t{\"/cona\", true, \"\", nil}, // key mismatch\n\t\t{\"/no\", true, \"\", nil}, // no matching child\n\t\t{\"/ab\", false, \"/ab\", nil},\n\t\t{\"/α\", false, \"/α\", nil},\n\t\t{\"/β\", false, \"/β\", nil},\n\t})\n\n\tcheckPriorities(t, tree)\n}"} {"repo":"gin","file":"tree_test.go","line":138,"symbol":"TestTreeWildcard","kind":"function","lang":"go","code":"func TestTreeWildcard(t *testing.T) {\n\ttree := &node{}\n\n\troutes := [...]string{\n\t\t\"/\",\n\t\t\"/cmd/:tool/\",\n\t\t\"/cmd/:tool/:sub\",\n\t\t\"/cmd/whoami\",\n\t\t\"/cmd/whoami/root\",\n\t\t\"/cmd/whoami/root/\",\n\t\t\"/src/*filepath\",\n\t\t\"/search/\",\n\t\t\"/search/:query\",\n\t\t\"/search/gin-gonic\",\n\t\t\"/search/google\",\n\t\t\"/user_:name\",\n\t\t\"/user_:name/about\",\n\t\t\"/files/:dir/*filepath\",\n\t\t\"/doc/\",\n\t\t\"/doc/go_faq.html\",\n\t\t\"/doc/go1.html\",\n\t\t\"/info/:user/public\",\n\t\t\"/info/:user/project/:project\",\n\t\t\"/info/:user/project/golang\",\n\t\t\"/aa/*xx\",\n\t\t\"/ab/*xx\",\n\t\t\"/:cc\",\n\t\t\"/c1/:dd/e\",\n\t\t\"/c1/:dd/e1\",\n\t\t\"/:cc/cc\",\n\t\t\"/:cc/:dd/ee\",\n\t\t\"/:cc/:dd/:ee/ff\",\n\t\t\"/:cc/:dd/:ee/:ff/gg\",\n\t\t\"/:cc/:dd/:ee/:ff/:gg/hh\",\n\t\t\"/get/test/abc/\",\n\t\t\"/get/:param/abc/\",\n\t\t\"/something/:paramname/thirdthing\",\n\t\t\"/something/secondthing/test\",\n\t\t\"/get/abc\",\n\t\t\"/get/:param\",\n\t\t\"/get/abc/123abc\",\n\t\t\"/get/abc/:param\",\n\t\t\"/get/abc/123abc/xxx8\",\n\t\t\"/get/abc/123abc/:param\",\n\t\t\"/get/abc/123abc/xxx8/1234\",\n\t\t\"/get/abc/123abc/xxx8/:param\",\n\t\t\"/get/abc/123abc/xxx8/1234/ffas\",\n\t\t\"/get/abc/123abc/xxx8/1234/:param\",\n\t\t\"/get/abc/123abc/xxx8/1234/kkdd/12c\",\n\t\t\"/get/abc/123abc/xxx8/1234/kkdd/:param\",\n\t\t\"/get/abc/:param/test\",\n\t\t\"/get/abc/123abd/:param\",\n\t\t\"/get/abc/123abddd"} {"repo":"gin","file":"tree_test.go","line":325,"symbol":"TestUnescapeParameters","kind":"function","lang":"go","code":"func TestUnescapeParameters(t *testing.T) {\n\ttree := &node{}\n\n\troutes := [...]string{\n\t\t\"/\",\n\t\t\"/cmd/:tool/:sub\",\n\t\t\"/cmd/:tool/\",\n\t\t\"/src/*filepath\",\n\t\t\"/search/:query\",\n\t\t\"/files/:dir/*filepath\",\n\t\t\"/info/:user/project/:project\",\n\t\t\"/info/:user\",\n\t}\n\tfor _, route := range routes {\n\t\ttree.addRoute(route, fakeHandler(route))\n\t}\n\n\tunescape := true\n\tcheckRequests(t, tree, testRequests{\n\t\t{\"/\", false, \"/\", nil},\n\t\t{\"/cmd/test/\", false, \"/cmd/:tool/\", Params{Param{Key: \"tool\", Value: \"test\"}}},\n\t\t{\"/cmd/test\", true, \"\", Params{Param{Key: \"tool\", Value: \"test\"}}},\n\t\t{\"/src/some/file.png\", false, \"/src/*filepath\", Params{Param{Key: \"filepath\", Value: \"/some/file.png\"}}},\n\t\t{\"/src/some/file+test.png\", false, \"/src/*filepath\", Params{Param{Key: \"filepath\", Value: \"/some/file test.png\"}}},\n\t\t{\"/src/some/file++++%%%%test.png\", false, \"/src/*filepath\", Params{Param{Key: \"filepath\", Value: \"/some/file++++%%%%test.png\"}}},\n\t\t{\"/src/some/file%2Ftest.png\", false, \"/src/*filepath\", Params{Param{Key: \"filepath\", Value: \"/some/file/test.png\"}}},\n\t\t{\"/search/someth!ng+in+ünìcodé\", false, \"/search/:query\", Params{Param{Key: \"query\", Value: \"someth!ng in ünìcodé\"}}},\n\t\t{\"/info/gordon/project/go\", false"} {"repo":"gin","file":"tree_test.go","line":362,"symbol":"catchPanic","kind":"function","lang":"go","code":"func catchPanic(testFunc func()) (recv any) {\n\tdefer func() {\n\t\trecv = recover()\n\t}()\n\n\ttestFunc()\n\treturn\n}"} {"repo":"gin","file":"tree_test.go","line":371,"symbol":"testRoute","kind":"type","lang":"go","code":"type testRoute struct {\n\tpath string\n\tconflict bool\n}"} {"repo":"gin","file":"tree_test.go","line":376,"symbol":"testRoutes","kind":"function","lang":"go","code":"func testRoutes(t *testing.T, routes []testRoute) {\n\ttree := &node{}\n\n\tfor _, route := range routes {\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(route.path, nil)\n\t\t})\n\n\t\tif route.conflict {\n\t\t\tif recv == nil {\n\t\t\t\tt.Errorf(\"no panic for conflicting route '%s'\", route.path)\n\t\t\t}\n\t\t} else if recv != nil {\n\t\t\tt.Errorf(\"unexpected panic for route '%s': %v\", route.path, recv)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":394,"symbol":"TestTreeWildcardConflict","kind":"function","lang":"go","code":"func TestTreeWildcardConflict(t *testing.T) {\n\troutes := []testRoute{\n\t\t{\"/cmd/:tool/:sub\", false},\n\t\t{\"/cmd/vet\", false},\n\t\t{\"/foo/bar\", false},\n\t\t{\"/foo/:name\", false},\n\t\t{\"/foo/:names\", true},\n\t\t{\"/cmd/*path\", true},\n\t\t{\"/cmd/:badvar\", true},\n\t\t{\"/cmd/:tool/names\", false},\n\t\t{\"/cmd/:tool/:badsub/details\", true},\n\t\t{\"/src/*filepath\", false},\n\t\t{\"/src/:file\", true},\n\t\t{\"/src/static.json\", true},\n\t\t{\"/src/*filepathx\", true},\n\t\t{\"/src/\", true},\n\t\t{\"/src/foo/bar\", true},\n\t\t{\"/src1/\", false},\n\t\t{\"/src1/*filepath\", true},\n\t\t{\"/src2*filepath\", true},\n\t\t{\"/src2/*filepath\", false},\n\t\t{\"/search/:query\", false},\n\t\t{\"/search/valid\", false},\n\t\t{\"/user_:name\", false},\n\t\t{\"/user_x\", false},\n\t\t{\"/user_:name\", false},\n\t\t{\"/id:id\", false},\n\t\t{\"/id/:id\", false},\n\t\t{\"/static/*file\", false},\n\t\t{\"/static/\", true},\n\t\t{\"/escape/test\\\\:d1\", false},\n\t\t{\"/escape/test\\\\:d2\", false},\n\t\t{\"/escape/test:param\", false},\n\t}\n\ttestRoutes(t, routes)\n}"} {"repo":"gin","file":"tree_test.go","line":431,"symbol":"TestCatchAllAfterSlash","kind":"function","lang":"go","code":"func TestCatchAllAfterSlash(t *testing.T) {\n\troutes := []testRoute{\n\t\t{\"/non-leading-*catchall\", true},\n\t}\n\ttestRoutes(t, routes)\n}"} {"repo":"gin","file":"tree_test.go","line":438,"symbol":"TestTreeChildConflict","kind":"function","lang":"go","code":"func TestTreeChildConflict(t *testing.T) {\n\troutes := []testRoute{\n\t\t{\"/cmd/vet\", false},\n\t\t{\"/cmd/:tool\", false},\n\t\t{\"/cmd/:tool/:sub\", false},\n\t\t{\"/cmd/:tool/misc\", false},\n\t\t{\"/cmd/:tool/:othersub\", true},\n\t\t{\"/src/AUTHORS\", false},\n\t\t{\"/src/*filepath\", true},\n\t\t{\"/user_x\", false},\n\t\t{\"/user_:name\", false},\n\t\t{\"/id/:id\", false},\n\t\t{\"/id:id\", false},\n\t\t{\"/:id\", false},\n\t\t{\"/*filepath\", true},\n\t}\n\ttestRoutes(t, routes)\n}"} {"repo":"gin","file":"tree_test.go","line":457,"symbol":"TestTreeDuplicatePath","kind":"function","lang":"go","code":"func TestTreeDuplicatePath(t *testing.T) {\n\ttree := &node{}\n\n\troutes := [...]string{\n\t\t\"/\",\n\t\t\"/doc/\",\n\t\t\"/src/*filepath\",\n\t\t\"/search/:query\",\n\t\t\"/user_:name\",\n\t}\n\tfor _, route := range routes {\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(route, fakeHandler(route))\n\t\t})\n\t\tif recv != nil {\n\t\t\tt.Fatalf(\"panic inserting route '%s': %v\", route, recv)\n\t\t}\n\n\t\t// Add again\n\t\trecv = catchPanic(func() {\n\t\t\ttree.addRoute(route, nil)\n\t\t})\n\t\tif recv == nil {\n\t\t\tt.Fatalf(\"no panic while inserting duplicate route '%s\", route)\n\t\t}\n\t}\n\n\t// printChildren(tree, \"\")\n\n\tcheckRequests(t, tree, testRequests{\n\t\t{\"/\", false, \"/\", nil},\n\t\t{\"/doc/\", false, \"/doc/\", nil},\n\t\t{\"/src/some/file.png\", false, \"/src/*filepath\", Params{Param{\"filepath\", \"/some/file.png\"}}},\n\t\t{\"/search/someth!ng+in+ünìcodé\", false, \"/search/:query\", Params{Param{\"query\", \"someth!ng+in+ünìcodé\"}}},\n\t\t{\"/user_gopher\", false, \"/user_:name\", Params{Param{\"name\", \"gopher\"}}},\n\t})\n}"} {"repo":"gin","file":"tree_test.go","line":495,"symbol":"TestEmptyWildcardName","kind":"function","lang":"go","code":"func TestEmptyWildcardName(t *testing.T) {\n\ttree := &node{}\n\n\troutes := [...]string{\n\t\t\"/user:\",\n\t\t\"/user:/\",\n\t\t\"/cmd/:/\",\n\t\t\"/src/*\",\n\t}\n\tfor _, route := range routes {\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(route, nil)\n\t\t})\n\t\tif recv == nil {\n\t\t\tt.Fatalf(\"no panic while inserting route with empty wildcard name '%s\", route)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":514,"symbol":"TestTreeCatchAllConflict","kind":"function","lang":"go","code":"func TestTreeCatchAllConflict(t *testing.T) {\n\troutes := []testRoute{\n\t\t{\"/src/*filepath/x\", true},\n\t\t{\"/src2/\", false},\n\t\t{\"/src2/*filepath/x\", true},\n\t\t{\"/src3/*filepath\", false},\n\t\t{\"/src3/*filepath/x\", true},\n\t}\n\ttestRoutes(t, routes)\n}"} {"repo":"gin","file":"tree_test.go","line":525,"symbol":"TestTreeCatchAllConflictRoot","kind":"function","lang":"go","code":"func TestTreeCatchAllConflictRoot(t *testing.T) {\n\troutes := []testRoute{\n\t\t{\"/\", false},\n\t\t{\"/*filepath\", true},\n\t}\n\ttestRoutes(t, routes)\n}"} {"repo":"gin","file":"tree_test.go","line":533,"symbol":"TestTreeCatchMaxParams","kind":"function","lang":"go","code":"func TestTreeCatchMaxParams(t *testing.T) {\n\ttree := &node{}\n\troute := \"/cmd/*filepath\"\n\ttree.addRoute(route, fakeHandler(route))\n}"} {"repo":"gin","file":"tree_test.go","line":539,"symbol":"TestTreeDoubleWildcard","kind":"function","lang":"go","code":"func TestTreeDoubleWildcard(t *testing.T) {\n\tconst panicMsg = \"only one wildcard per path segment is allowed\"\n\n\troutes := [...]string{\n\t\t\"/:foo:bar\",\n\t\t\"/:foo:bar/\",\n\t\t\"/:foo*bar\",\n\t}\n\n\tfor _, route := range routes {\n\t\ttree := &node{}\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(route, nil)\n\t\t})\n\n\t\tif rs, ok := recv.(string); !ok || !strings.HasPrefix(rs, panicMsg) {\n\t\t\tt.Fatalf(`\"Expected panic \"%s\" for route '%s', got \"%v\"`, panicMsg, route, recv)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":540,"symbol":"panicMsg","kind":"constant","lang":"go","code":"panicMsg = \"only one wildcard per path segment is allowed\""} {"repo":"gin","file":"tree_test.go","line":570,"symbol":"TestTreeTrailingSlashRedirect","kind":"function","lang":"go","code":"func TestTreeTrailingSlashRedirect(t *testing.T) {\n\ttree := &node{}\n\n\troutes := [...]string{\n\t\t\"/hi\",\n\t\t\"/b/\",\n\t\t\"/search/:query\",\n\t\t\"/cmd/:tool/\",\n\t\t\"/src/*filepath\",\n\t\t\"/x\",\n\t\t\"/x/y\",\n\t\t\"/y/\",\n\t\t\"/y/z\",\n\t\t\"/0/:id\",\n\t\t\"/0/:id/1\",\n\t\t\"/1/:id/\",\n\t\t\"/1/:id/2\",\n\t\t\"/aa\",\n\t\t\"/a/\",\n\t\t\"/admin\",\n\t\t\"/admin/:category\",\n\t\t\"/admin/:category/:page\",\n\t\t\"/doc\",\n\t\t\"/doc/go_faq.html\",\n\t\t\"/doc/go1.html\",\n\t\t\"/no/a\",\n\t\t\"/no/b\",\n\t\t\"/api/:page/:name\",\n\t\t\"/api/hello/:name/bar/\",\n\t\t\"/api/bar/:name\",\n\t\t\"/api/baz/foo\",\n\t\t\"/api/baz/foo/bar\",\n\t\t\"/blog/:p\",\n\t\t\"/posts/:b/:c\",\n\t\t\"/posts/b/:c/d/\",\n\t\t\"/vendor/:x/*y\",\n\t}\n\tfor _, route := range routes {\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(route, fakeHandler(route))\n\t\t})\n\t\tif recv != nil {\n\t\t\tt.Fatalf(\"panic inserting route '%s': %v\", route, recv)\n\t\t}\n\t}\n\n\ttsrRoutes := [...]string{\n\t\t\"/hi/\",\n\t\t\"/b\",\n\t\t\"/search/gopher/\",\n\t\t\"/cmd/vet\",\n\t\t\"/src\",\n\t\t\"/x/\",\n\t\t\"/y\",\n\t\t\"/0/go/\",\n\t\t\"/1/go\",\n\t\t\"/a\",\n\t\t\"/admin/\",\n\t\t\"/admin/config/\",\n\t\t\"/admin/config/permissions/\",\n\t\t\"/doc/\",\n\t\t\"/admin/static/\",\n\t\t\"/admin/cfg/\",\n\t\t\"/admin/cfg/users/\",\n\t\t\"/api/hello/x/bar\",\n\t\t\"/api/baz/foo/\",\n\t\t\"/api/baz/bax/\",\n\t\t\"/api/bar/huh/\",\n\t\t\"/api/baz/foo/bar/\",\n\t\t\"/api/world/abc/\",\n\t\t\"/blog/pp/"} {"repo":"gin","file":"tree_test.go","line":676,"symbol":"TestTreeRootTrailingSlashRedirect","kind":"function","lang":"go","code":"func TestTreeRootTrailingSlashRedirect(t *testing.T) {\n\ttree := &node{}\n\n\trecv := catchPanic(func() {\n\t\ttree.addRoute(\"/:test\", fakeHandler(\"/:test\"))\n\t})\n\tif recv != nil {\n\t\tt.Fatalf(\"panic inserting test route: %v\", recv)\n\t}\n\n\tvalue := tree.getValue(\"/\", nil, getSkippedNodes(), false)\n\tif value.handlers != nil {\n\t\tt.Fatalf(\"non-nil handler\")\n\t} else if value.tsr {\n\t\tt.Errorf(\"expected no TSR recommendation\")\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":694,"symbol":"TestRedirectTrailingSlash","kind":"function","lang":"go","code":"func TestRedirectTrailingSlash(t *testing.T) {\n\tdata := []struct {\n\t\tpath string\n\t}{\n\t\t{\"/hello/:name\"},\n\t\t{\"/hello/:name/123\"},\n\t\t{\"/hello/:name/234\"},\n\t}\n\n\tnode := &node{}\n\tfor _, item := range data {\n\t\tnode.addRoute(item.path, fakeHandler(\"test\"))\n\t}\n\n\tvalue := node.getValue(\"/hello/abx/\", nil, getSkippedNodes(), false)\n\tif value.tsr != true {\n\t\tt.Fatalf(\"want true, is false\")\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":714,"symbol":"TestTreeFindCaseInsensitivePath","kind":"function","lang":"go","code":"func TestTreeFindCaseInsensitivePath(t *testing.T) {\n\ttree := &node{}\n\n\tlongPath := \"/l\" + strings.Repeat(\"o\", 128) + \"ng\"\n\tlOngPath := \"/l\" + strings.Repeat(\"O\", 128) + \"ng/\"\n\n\troutes := [...]string{\n\t\t\"/hi\",\n\t\t\"/b/\",\n\t\t\"/ABC/\",\n\t\t\"/search/:query\",\n\t\t\"/cmd/:tool/\",\n\t\t\"/src/*filepath\",\n\t\t\"/x\",\n\t\t\"/x/y\",\n\t\t\"/y/\",\n\t\t\"/y/z\",\n\t\t\"/0/:id\",\n\t\t\"/0/:id/1\",\n\t\t\"/1/:id/\",\n\t\t\"/1/:id/2\",\n\t\t\"/aa\",\n\t\t\"/a/\",\n\t\t\"/doc\",\n\t\t\"/doc/go_faq.html\",\n\t\t\"/doc/go1.html\",\n\t\t\"/doc/go/away\",\n\t\t\"/no/a\",\n\t\t\"/no/b\",\n\t\t\"/Π\",\n\t\t\"/u/apfêl/\",\n\t\t\"/u/äpfêl/\",\n\t\t\"/u/öpfêl\",\n\t\t\"/v/Äpfêl/\",\n\t\t\"/v/Öpfêl\",\n\t\t\"/w/♬\", // 3 byte\n\t\t\"/w/♭/\", // 3 byte, last byte differs\n\t\t\"/w/𠜎\", // 4 byte\n\t\t\"/w/𠜏/\", // 4 byte\n\t\tlongPath,\n\t}\n\n\tfor _, route := range routes {\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(route, fakeHandler(route))\n\t\t})\n\t\tif recv != nil {\n\t\t\tt.Fatalf(\"panic inserting route '%s': %v\", route, recv)\n\t\t}\n\t}\n\n\t// Check out == in for all registered routes\n\t// With fixTrailingSlash = true\n\tfor _, route := range routes {\n\t\tout, found := tree.findCaseInsensitivePath(route, true)\n\t\tif !found {\n\t\t\tt.Errorf(\"Route '%s' not found!\", route)\n\t\t} else if string(out) != route {\n\t\t\tt.Errorf(\"Wrong result for route '%s': %s\", route, s"} {"repo":"gin","file":"tree_test.go","line":874,"symbol":"TestTreeInvalidNodeType","kind":"function","lang":"go","code":"func TestTreeInvalidNodeType(t *testing.T) {\n\tconst panicMsg = \"invalid node type\"\n\n\ttree := &node{}\n\ttree.addRoute(\"/\", fakeHandler(\"/\"))\n\ttree.addRoute(\"/:page\", fakeHandler(\"/:page\"))\n\n\t// set invalid node type\n\ttree.children[0].nType = 42\n\n\t// normal lookup\n\trecv := catchPanic(func() {\n\t\ttree.getValue(\"/test\", nil, getSkippedNodes(), false)\n\t})\n\tif rs, ok := recv.(string); !ok || rs != panicMsg {\n\t\tt.Fatalf(\"Expected panic '\"+panicMsg+\"', got '%v'\", recv)\n\t}\n\n\t// case-insensitive lookup\n\trecv = catchPanic(func() {\n\t\ttree.findCaseInsensitivePath(\"/test\", true)\n\t})\n\tif rs, ok := recv.(string); !ok || rs != panicMsg {\n\t\tt.Fatalf(\"Expected panic '\"+panicMsg+\"', got '%v'\", recv)\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":875,"symbol":"panicMsg","kind":"constant","lang":"go","code":"panicMsg = \"invalid node type\""} {"repo":"gin","file":"tree_test.go","line":901,"symbol":"TestTreeInvalidParamsType","kind":"function","lang":"go","code":"func TestTreeInvalidParamsType(t *testing.T) {\n\ttree := &node{}\n\t// add a child with wildcard\n\troute := \"/:path\"\n\ttree.addRoute(route, fakeHandler(route))\n\n\t// set invalid Params type\n\tparams := make(Params, 0)\n\n\t// try to trigger slice bounds out of range with capacity 0\n\ttree.getValue(\"/test\", ¶ms, getSkippedNodes(), false)\n}"} {"repo":"gin","file":"tree_test.go","line":914,"symbol":"TestTreeExpandParamsCapacity","kind":"function","lang":"go","code":"func TestTreeExpandParamsCapacity(t *testing.T) {\n\tdata := []struct {\n\t\tpath string\n\t}{\n\t\t{\"/:path\"},\n\t\t{\"/*path\"},\n\t}\n\n\tfor _, item := range data {\n\t\ttree := &node{}\n\t\ttree.addRoute(item.path, fakeHandler(item.path))\n\t\tparams := make(Params, 0)\n\n\t\tvalue := tree.getValue(\"/test\", ¶ms, getSkippedNodes(), false)\n\n\t\tif value.params == nil {\n\t\t\tt.Errorf(\"Expected %s params to be set, but they weren't\", item.path)\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(*value.params) != 1 {\n\t\t\tt.Errorf(\"Wrong number of %s params: got %d, want %d\",\n\t\t\t\titem.path, len(*value.params), 1)\n\t\t\tcontinue\n\t\t}\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":942,"symbol":"TestTreeWildcardConflictEx","kind":"function","lang":"go","code":"func TestTreeWildcardConflictEx(t *testing.T) {\n\tconflicts := [...]struct {\n\t\troute string\n\t\tsegPath string\n\t\texistPath string\n\t\texistSegPath string\n\t}{\n\t\t{\"/who/are/foo\", \"/foo\", `/who/are/\\*you`, `/\\*you`},\n\t\t{\"/who/are/foo/\", \"/foo/\", `/who/are/\\*you`, `/\\*you`},\n\t\t{\"/who/are/foo/bar\", \"/foo/bar\", `/who/are/\\*you`, `/\\*you`},\n\t\t{\"/con:nection\", \":nection\", `/con:tact`, `:tact`},\n\t}\n\n\tfor _, conflict := range conflicts {\n\t\t// I have to re-create a 'tree', because the 'tree' will be\n\t\t// in an inconsistent state when the loop recovers from the\n\t\t// panic which threw by 'addRoute' function.\n\t\ttree := &node{}\n\t\troutes := [...]string{\n\t\t\t\"/con:tact\",\n\t\t\t\"/who/are/*you\",\n\t\t\t\"/who/foo/hello\",\n\t\t}\n\n\t\tfor _, route := range routes {\n\t\t\ttree.addRoute(route, fakeHandler(route))\n\t\t}\n\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(conflict.route, fakeHandler(conflict.route))\n\t\t})\n\n\t\tif !regexp.MustCompile(fmt.Sprintf(\"'%s' in new path .* conflicts with existing wildcard '%s' in existing prefix '%s'\", conflict.segPath, conflict.existSegPath, conflict.existPath)).MatchString(fmt.Sprint(recv)) {\n\t\t\tt.Fatalf(\"invalid wildcard conflict error (%v)\", recv)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":980,"symbol":"TestTreeInvalidEscape","kind":"function","lang":"go","code":"func TestTreeInvalidEscape(t *testing.T) {\n\troutes := map[string]bool{\n\t\t\"/r1/r\": true,\n\t\t\"/r2/:r\": true,\n\t\t\"/r3/\\\\:r\": true,\n\t}\n\ttree := &node{}\n\tfor route, valid := range routes {\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(route, fakeHandler(route))\n\t\t})\n\t\tif recv == nil != valid {\n\t\t\tt.Fatalf(\"%s should be %t but got %v\", route, valid, recv)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":997,"symbol":"TestWildcardInvalidSlash","kind":"function","lang":"go","code":"func TestWildcardInvalidSlash(t *testing.T) {\n\tconst panicMsgPrefix = \"no / before catch-all in path\"\n\n\troutes := map[string]bool{\n\t\t\"/foo/bar\": true,\n\t\t\"/foo/x*zy\": false,\n\t\t\"/foo/b*r\": false,\n\t}\n\n\tfor route, valid := range routes {\n\t\ttree := &node{}\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(route, nil)\n\t\t})\n\n\t\tif recv == nil != valid {\n\t\t\tt.Fatalf(\"%s should be %t but got %v\", route, valid, recv)\n\t\t}\n\n\t\tif rs, ok := recv.(string); recv != nil && (!ok || !strings.HasPrefix(rs, panicMsgPrefix)) {\n\t\t\tt.Fatalf(`\"Expected panic \"%s\" for route '%s', got \"%v\"`, panicMsgPrefix, route, recv)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"tree_test.go","line":998,"symbol":"panicMsgPrefix","kind":"constant","lang":"go","code":"panicMsgPrefix = \"no / before catch-all in path\""} {"repo":"gin","file":"tree_test.go","line":1022,"symbol":"TestTreeFindCaseInsensitivePathWithMultipleChildrenAndWildcard","kind":"function","lang":"go","code":"func TestTreeFindCaseInsensitivePathWithMultipleChildrenAndWildcard(t *testing.T) {\n\ttree := &node{}\n\n\t// Setup routes that create a node with both static children and a wildcard child.\n\t// This configuration previously caused a panic (\"invalid node type\") in\n\t// findCaseInsensitivePathRec because it accessed children[0] instead of the\n\t// wildcard child (which is always at the end of the children array).\n\t// See: https://github.com/gin-gonic/gin/issues/2959\n\troutes := [...]string{\n\t\t\"/aa/aa\",\n\t\t\"/:bb/aa\",\n\t}\n\n\tfor _, route := range routes {\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(route, fakeHandler(route))\n\t\t})\n\t\tif recv != nil {\n\t\t\tt.Fatalf(\"panic inserting route '%s': %v\", route, recv)\n\t\t}\n\t}\n\n\t// These lookups previously panicked with \"invalid node type\" because\n\t// findCaseInsensitivePathRec picked children[0] (a static node) instead\n\t// of the wildcard child at the end of the array.\n\tout, found := tree.findCaseInsensitivePath(\"/aa\", true)\n\tif found {\n\t\tt.Errorf(\"Expected no match for '/aa', but got: %s\", string(out))\n\t}\n\n\tout, found = tree.findCaseInsensitivePath(\"/aa/aa/aa/aa\", true)\n\tif found {\n\t\tt.Errorf(\"Expected no match for '/aa/aa/aa/aa', but got: %s\", string(ou"} {"repo":"gin","file":"tree_test.go","line":1066,"symbol":"TestTreeFindCaseInsensitivePathWildcardParamAndStaticChild","kind":"function","lang":"go","code":"func TestTreeFindCaseInsensitivePathWildcardParamAndStaticChild(t *testing.T) {\n\ttree := &node{}\n\n\t// Another variant: param route + static route under same prefix\n\troutes := [...]string{\n\t\t\"/prefix/:id\",\n\t\t\"/prefix/xxx\",\n\t}\n\n\tfor _, route := range routes {\n\t\trecv := catchPanic(func() {\n\t\t\ttree.addRoute(route, fakeHandler(route))\n\t\t})\n\t\tif recv != nil {\n\t\t\tt.Fatalf(\"panic inserting route '%s': %v\", route, recv)\n\t\t}\n\t}\n\n\t// Should NOT panic even for paths that don't match any route\n\tout, found := tree.findCaseInsensitivePath(\"/prefix/a/b/c\", true)\n\tif found {\n\t\tt.Errorf(\"Expected no match for '/prefix/a/b/c', but got: %s\", string(out))\n\t}\n\n\t// Exact match should still work\n\tout, found = tree.findCaseInsensitivePath(\"/prefix/xxx\", true)\n\tif !found {\n\t\tt.Error(\"Route '/prefix/xxx' not found\")\n\t} else if string(out) != \"/prefix/xxx\" {\n\t\tt.Errorf(\"Wrong result for '/prefix/xxx': %s\", string(out))\n\t}\n\n\t// Case-insensitive match should work\n\tout, found = tree.findCaseInsensitivePath(\"/PREFIX/XXX\", true)\n\tif !found {\n\t\tt.Error(\"Route '/PREFIX/XXX' not found via case-insensitive lookup\")\n\t} else if string(out) != \"/prefix/xxx\" {\n\t\tt.Errorf(\"Wrong result for '/PREFIX/XXX': expected '/prefix/"} {"repo":"gin","file":"utils.go","line":20,"symbol":"BindKey","kind":"constant","lang":"go","doc":"BindKey indicates a default bind key.","code":"BindKey = \"_gin-gonic/gin/bindkey\""} {"repo":"gin","file":"utils.go","line":23,"symbol":"localhostIP","kind":"constant","lang":"go","doc":"localhostIP indicates the default localhost IP address.","code":"localhostIP = \"127.0.0.1\""} {"repo":"gin","file":"utils.go","line":26,"symbol":"localhostIPv6","kind":"constant","lang":"go","doc":"localhostIPv6 indicates the default localhost IPv6 address.","code":"localhostIPv6 = \"::1\""} {"repo":"gin","file":"utils.go","line":30,"symbol":"Bind","kind":"function","lang":"go","doc":"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{})).","code":"func Bind(val any) HandlerFunc {\n\tvalue := reflect.ValueOf(val)\n\tif value.Kind() == reflect.Ptr {\n\t\tpanic(`Bind struct can not be a pointer. Example:\n\tUse: gin.Bind(Struct{}) instead of gin.Bind(&Struct{})\n`)\n\t}\n\ttyp := value.Type()\n\n\treturn func(c *Context) {\n\t\tobj := reflect.New(typ).Interface()\n\t\tif c.Bind(obj) == nil {\n\t\t\tc.Set(BindKey, obj)\n\t\t}\n\t}\n}"} {"repo":"gin","file":"utils.go","line":48,"symbol":"WrapF","kind":"function","lang":"go","doc":"WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware.","code":"func WrapF(f http.HandlerFunc) HandlerFunc {\n\treturn func(c *Context) {\n\t\tf(c.Writer, c.Request)\n\t}\n}"} {"repo":"gin","file":"utils.go","line":55,"symbol":"WrapH","kind":"function","lang":"go","doc":"WrapH is a helper function for wrapping http.Handler and returns a Gin middleware.","code":"func WrapH(h http.Handler) HandlerFunc {\n\treturn func(c *Context) {\n\t\th.ServeHTTP(c.Writer, c.Request)\n\t}\n}"} {"repo":"gin","file":"utils.go","line":62,"symbol":"H","kind":"type","lang":"go","doc":"H is a shortcut for map[string]any","code":"type H map[string]any"} {"repo":"gin","file":"utils.go","line":65,"symbol":"MarshalXML","kind":"method","lang":"go","doc":"MarshalXML allows type H to be used with xml.Marshal.","code":"func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Name = xml.Name{\n\t\tSpace: \"\",\n\t\tLocal: \"map\",\n\t}\n\tif err := e.EncodeToken(start); err != nil {\n\t\treturn err\n\t}\n\tfor key, value := range h {\n\t\telem := xml.StartElement{\n\t\t\tName: xml.Name{Space: \"\", Local: key},\n\t\t\tAttr: []xml.Attr{},\n\t\t}\n\t\tif err := e.EncodeElement(value, elem); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn e.EncodeToken(xml.EndElement{Name: start.Name})\n}"} {"repo":"gin","file":"utils.go","line":86,"symbol":"assert1","kind":"function","lang":"go","code":"func assert1(guard bool, text string) {\n\tif !guard {\n\t\tpanic(text)\n\t}\n}"} {"repo":"gin","file":"utils.go","line":92,"symbol":"filterFlags","kind":"function","lang":"go","code":"func filterFlags(content string) string {\n\tfor i, char := range content {\n\t\tif char == ' ' || char == ';' {\n\t\t\treturn content[:i]\n\t\t}\n\t}\n\treturn content\n}"} {"repo":"gin","file":"utils.go","line":101,"symbol":"chooseData","kind":"function","lang":"go","code":"func chooseData(custom, wildcard any) any {\n\tif custom != nil {\n\t\treturn custom\n\t}\n\tif wildcard != nil {\n\t\treturn wildcard\n\t}\n\tpanic(\"negotiation config is invalid\")\n}"} {"repo":"gin","file":"utils.go","line":111,"symbol":"parseAccept","kind":"function","lang":"go","code":"func parseAccept(acceptHeader string) []string {\n\tparts := strings.Split(acceptHeader, \",\")\n\tout := make([]string, 0, len(parts))\n\tfor _, part := range parts {\n\t\tif i := strings.IndexByte(part, ';'); i > 0 {\n\t\t\tpart = part[:i]\n\t\t}\n\t\tif part = strings.TrimSpace(part); part != \"\" {\n\t\t\tout = append(out, part)\n\t\t}\n\t}\n\treturn out\n}"} {"repo":"gin","file":"utils.go","line":125,"symbol":"lastChar","kind":"function","lang":"go","code":"func lastChar(str string) uint8 {\n\tif str == \"\" {\n\t\tpanic(\"The length of the string can't be 0\")\n\t}\n\treturn str[len(str)-1]\n}"} {"repo":"gin","file":"utils.go","line":132,"symbol":"nameOfFunction","kind":"function","lang":"go","code":"func nameOfFunction(f any) string {\n\treturn runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()\n}"} {"repo":"gin","file":"utils.go","line":136,"symbol":"joinPaths","kind":"function","lang":"go","code":"func joinPaths(absolutePath, relativePath string) string {\n\tif relativePath == \"\" {\n\t\treturn absolutePath\n\t}\n\n\tfinalPath := path.Join(absolutePath, relativePath)\n\tif lastChar(relativePath) == '/' && lastChar(finalPath) != '/' {\n\t\treturn finalPath + \"/\"\n\t}\n\treturn finalPath\n}"} {"repo":"gin","file":"utils.go","line":148,"symbol":"resolveAddress","kind":"function","lang":"go","code":"func resolveAddress(addr []string) string {\n\tswitch len(addr) {\n\tcase 0:\n\t\tif port := os.Getenv(\"PORT\"); port != \"\" {\n\t\t\tdebugPrint(\"Environment variable PORT=\\\"%s\\\"\", port)\n\t\t\treturn \":\" + port\n\t\t}\n\t\tdebugPrint(\"Environment variable PORT is undefined. Using port :8080 by default\")\n\t\treturn \":8080\"\n\tcase 1:\n\t\treturn addr[0]\n\tdefault:\n\t\tpanic(\"too many parameters\")\n\t}\n}"} {"repo":"gin","file":"utils.go","line":166,"symbol":"isASCII","kind":"function","lang":"go","doc":"isASCII reports whether s contains only ASCII characters. See https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters.","code":"func isASCII(s string) bool {\n\tfor i := range len(s) {\n\t\tif s[i] > unicode.MaxASCII {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}"} {"repo":"gin","file":"utils.go","line":176,"symbol":"safeInt8","kind":"function","lang":"go","doc":"safeInt8 converts int to int8 safely, capping at math.MaxInt8","code":"func safeInt8(n int) int8 {\n\tif n > math.MaxInt8 {\n\t\treturn math.MaxInt8\n\t}\n\treturn int8(n)\n}"} {"repo":"gin","file":"utils.go","line":184,"symbol":"safeUint16","kind":"function","lang":"go","doc":"safeUint16 converts int to uint16 safely, capping at math.MaxUint16","code":"func safeUint16(n int) uint16 {\n\tif n > math.MaxUint16 {\n\t\treturn math.MaxUint16\n\t}\n\treturn uint16(n)\n}"} {"repo":"gin","file":"utils_test.go","line":19,"symbol":"init","kind":"function","lang":"go","code":"func init() {\n\tSetMode(TestMode)\n}"} {"repo":"gin","file":"utils_test.go","line":23,"symbol":"BenchmarkParseAccept","kind":"function","lang":"go","code":"func BenchmarkParseAccept(b *testing.B) {\n\tfor b.Loop() {\n\t\tparseAccept(\"text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8\")\n\t}\n}"} {"repo":"gin","file":"utils_test.go","line":29,"symbol":"testStruct","kind":"type","lang":"go","code":"type testStruct struct {\n\tT *testing.T\n}"} {"repo":"gin","file":"utils_test.go","line":33,"symbol":"ServeHTTP","kind":"method","lang":"go","code":"func (t *testStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tassert.Equal(t.T, http.MethodPost, req.Method)\n\tassert.Equal(t.T, \"/path\", req.URL.Path)\n\tw.WriteHeader(http.StatusInternalServerError)\n\tfmt.Fprint(w, \"hello\")\n}"} {"repo":"gin","file":"utils_test.go","line":40,"symbol":"TestWrap","kind":"function","lang":"go","code":"func TestWrap(t *testing.T) {\n\trouter := New()\n\trouter.POST(\"/path\", WrapH(&testStruct{t}))\n\trouter.GET(\"/path2\", WrapF(func(w http.ResponseWriter, req *http.Request) {\n\t\tassert.Equal(t, http.MethodGet, req.Method)\n\t\tassert.Equal(t, \"/path2\", req.URL.Path)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprint(w, \"hola!\")\n\t}))\n\n\tw := PerformRequest(router, http.MethodPost, \"/path\")\n\tassert.Equal(t, http.StatusInternalServerError, w.Code)\n\tassert.Equal(t, \"hello\", w.Body.String())\n\n\tw = PerformRequest(router, http.MethodGet, \"/path2\")\n\tassert.Equal(t, http.StatusBadRequest, w.Code)\n\tassert.Equal(t, \"hola!\", w.Body.String())\n}"} {"repo":"gin","file":"utils_test.go","line":59,"symbol":"TestLastChar","kind":"function","lang":"go","code":"func TestLastChar(t *testing.T) {\n\tassert.Equal(t, uint8('a'), lastChar(\"hola\"))\n\tassert.Equal(t, uint8('s'), lastChar(\"adios\"))\n\tassert.Panics(t, func() { lastChar(\"\") })\n}"} {"repo":"gin","file":"utils_test.go","line":65,"symbol":"TestParseAccept","kind":"function","lang":"go","code":"func TestParseAccept(t *testing.T) {\n\tparts := parseAccept(\"text/html , application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8\")\n\tassert.Len(t, parts, 4)\n\tassert.Equal(t, \"text/html\", parts[0])\n\tassert.Equal(t, \"application/xhtml+xml\", parts[1])\n\tassert.Equal(t, \"application/xml\", parts[2])\n\tassert.Equal(t, \"*/*\", parts[3])\n}"} {"repo":"gin","file":"utils_test.go","line":74,"symbol":"TestChooseData","kind":"function","lang":"go","code":"func TestChooseData(t *testing.T) {\n\tA := \"a\"\n\tB := \"b\"\n\tassert.Equal(t, A, chooseData(A, B))\n\tassert.Equal(t, B, chooseData(nil, B))\n\tassert.Panics(t, func() { chooseData(nil, nil) })\n}"} {"repo":"gin","file":"utils_test.go","line":82,"symbol":"TestFilterFlags","kind":"function","lang":"go","code":"func TestFilterFlags(t *testing.T) {\n\tresult := filterFlags(\"text/html \")\n\tassert.Equal(t, \"text/html\", result)\n\n\tresult = filterFlags(\"text/html;\")\n\tassert.Equal(t, \"text/html\", result)\n}"} {"repo":"gin","file":"utils_test.go","line":90,"symbol":"TestFunctionName","kind":"function","lang":"go","code":"func TestFunctionName(t *testing.T) {\n\tassert.Regexp(t, `^(.*/vendor/)?github.com/gin-gonic/gin.somefunction$`, nameOfFunction(somefunction))\n}"} {"repo":"gin","file":"utils_test.go","line":94,"symbol":"somefunction","kind":"function","lang":"go","code":"func somefunction() {\n\t// this empty function is used by TestFunctionName()\n}"} {"repo":"gin","file":"utils_test.go","line":98,"symbol":"TestJoinPaths","kind":"function","lang":"go","code":"func TestJoinPaths(t *testing.T) {\n\tassert.Empty(t, joinPaths(\"\", \"\"))\n\tassert.Equal(t, \"/\", joinPaths(\"\", \"/\"))\n\tassert.Equal(t, \"/a\", joinPaths(\"/a\", \"\"))\n\tassert.Equal(t, \"/a/\", joinPaths(\"/a/\", \"\"))\n\tassert.Equal(t, \"/a/\", joinPaths(\"/a/\", \"/\"))\n\tassert.Equal(t, \"/a/\", joinPaths(\"/a\", \"/\"))\n\tassert.Equal(t, \"/a/hola\", joinPaths(\"/a\", \"/hola\"))\n\tassert.Equal(t, \"/a/hola\", joinPaths(\"/a/\", \"/hola\"))\n\tassert.Equal(t, \"/a/hola/\", joinPaths(\"/a/\", \"/hola/\"))\n\tassert.Equal(t, \"/a/hola/\", joinPaths(\"/a/\", \"/hola//\"))\n}"} {"repo":"gin","file":"utils_test.go","line":111,"symbol":"bindTestStruct","kind":"type","lang":"go","code":"type bindTestStruct struct {\n\tFoo string `form:\"foo\" binding:\"required\"`\n\tBar int `form:\"bar\" binding:\"min=4\"`\n}"} {"repo":"gin","file":"utils_test.go","line":116,"symbol":"TestBindMiddleware","kind":"function","lang":"go","code":"func TestBindMiddleware(t *testing.T) {\n\tvar value *bindTestStruct\n\tvar called bool\n\trouter := New()\n\trouter.GET(\"/\", Bind(bindTestStruct{}), func(c *Context) {\n\t\tcalled = true\n\t\tvalue = c.MustGet(BindKey).(*bindTestStruct)\n\t})\n\tPerformRequest(router, http.MethodGet, \"/?foo=hola&bar=10\")\n\tassert.True(t, called)\n\tassert.Equal(t, \"hola\", value.Foo)\n\tassert.Equal(t, 10, value.Bar)\n\n\tcalled = false\n\tPerformRequest(router, http.MethodGet, \"/?foo=hola&bar=1\")\n\tassert.False(t, called)\n\n\tassert.Panics(t, func() {\n\t\tBind(&bindTestStruct{})\n\t})\n}"} {"repo":"gin","file":"utils_test.go","line":117,"symbol":"value","kind":"variable","lang":"go","code":"value *bindTestStruct"} {"repo":"gin","file":"utils_test.go","line":118,"symbol":"called","kind":"variable","lang":"go","code":"called bool"} {"repo":"gin","file":"utils_test.go","line":138,"symbol":"TestMarshalXMLforH","kind":"function","lang":"go","code":"func TestMarshalXMLforH(t *testing.T) {\n\th := H{\n\t\t\"\": \"test\",\n\t}\n\tvar b bytes.Buffer\n\tenc := xml.NewEncoder(&b)\n\tvar x xml.StartElement\n\te := h.MarshalXML(enc, x)\n\tassert.Error(t, e)\n}"} {"repo":"gin","file":"utils_test.go","line":142,"symbol":"b","kind":"variable","lang":"go","code":"b bytes.Buffer"} {"repo":"gin","file":"utils_test.go","line":144,"symbol":"x","kind":"variable","lang":"go","code":"x xml.StartElement"} {"repo":"gin","file":"utils_test.go","line":149,"symbol":"TestMarshalXMLforHSuccess","kind":"function","lang":"go","code":"func TestMarshalXMLforHSuccess(t *testing.T) {\n\th := H{\n\t\t\"key1\": \"value1\",\n\t\t\"key2\": 123,\n\t}\n\tdata, err := xml.Marshal(h)\n\trequire.NoError(t, err)\n\tassert.Contains(t, string(data), \"value1\")\n\tassert.Contains(t, string(data), \"123\")\n}"} {"repo":"gin","file":"utils_test.go","line":160,"symbol":"TestIsASCII","kind":"function","lang":"go","code":"func TestIsASCII(t *testing.T) {\n\tassert.True(t, isASCII(\"test\"))\n\tassert.False(t, isASCII(\"🧡💛💚💙💜\"))\n}"} {"repo":"gin","file":"utils_test.go","line":165,"symbol":"TestSafeInt8","kind":"function","lang":"go","code":"func TestSafeInt8(t *testing.T) {\n\tassert.Equal(t, int8(100), safeInt8(100))\n\tassert.Equal(t, int8(math.MaxInt8), safeInt8(int(math.MaxInt8)+123))\n}"} {"repo":"gin","file":"utils_test.go","line":170,"symbol":"TestSafeUint16","kind":"function","lang":"go","code":"func TestSafeUint16(t *testing.T) {\n\tassert.Equal(t, uint16(100), safeUint16(100))\n\tassert.Equal(t, uint16(math.MaxUint16), safeUint16(int(math.MaxUint16)+123))\n}"} {"repo":"gin","file":"version.go","line":8,"symbol":"Version","kind":"constant","lang":"go","doc":"Version is the current gin framework's version.","code":"Version = \"v1.12.0\""}