{"prefix": "Binder interface.\ntype DefaultBinder struct{}\n\n// BindUnmarshaler is the interface used to wrap the UnmarshalParam method.\n// Types that don't implement this, but do implement encoding.TextUnmarshaler\n// will use that interface instead.\ntype BindUnmarshaler interface {\n\t// UnmarshalParam decodes and assigns a value from an form or query param.\n\tUnmarshalParam(param string) error\n}\n\n// bindMultipleUnmarshaler is used by binder to unmarshal multiple values from request at once to\n// type implementing this int", "suffix": "]string) error\n}\n\n// BindPathValues binds path parameter values to bindable object\nfunc BindPathValues(c *Context, target any) error {\n\tparams := map[string][]string{}\n\tfor _, param := range c.PathValues() {\n\t\tparams[param.Name] = []string{param.Value}\n\t}\n", "middle": "erface. For example request could have multiple query fields `?a=1&a=2&b=test` in that case\n// for `a` following slice `[\"1\", \"2\"] will be passed to unmarshaller.\ntype bindMultipleUnmarshaler interface {\n\tUnmarshalParams(params [", "meta": {"filepath": "bind.go", "language": "go", "file_size": 14910, "cut_index": 921, "middle_length": 229}}
{"prefix": "rrors in binder. Useful along with `FailFast()` method\n\t\tto do binding and returns on first problem\n `BindErrors()` returns all bind errors from binder and resets errors in binder.\n\n\tTypes that are supported:\n\t\t* bool\n\t\t* float32\n\t\t* float64\n\t\t* int\n\t\t* int8\n\t\t* int16\n\t\t* int32\n\t\t* int64\n\t\t* uint\n\t\t* uint8/byte (does not support `bytes()`. Use BindUnmarshaler/CustomFunc to convert value from base64 etc to []byte{})\n\t\t* uint16\n\t\t* uint32\n\t\t* uint64\n\t\t* string\n\t\t* time\n\t\t* duration\n\t\t* BindUnmarshaler() inte", "suffix": "imeNano() - converts unix time with nanosecond precision (integer) to time.Time\n\t\t* CustomFunc() - callback function for your custom conversion logic. Signature `func(values []string) []error`\n*/\n\n// BindingError represents an error that occurred while bin", "middle": "rface\n\t\t* TextUnmarshaler() interface\n\t\t* JSONUnmarshaler() interface\n\t\t* UnixTime() - converts unix time (integer) to time.Time\n\t\t* UnixTimeMilli() - converts unix time with millisecond precision (integer) to time.Time\n\t\t* UnixT", "meta": {"filepath": "binder.go", "language": "go", "file_size": 43831, "cut_index": 2151, "middle_length": 229}}
{"prefix": "Name: cmp.Or(tc.givenKey, \"key\"),\n\t\t\t\tValue: tc.givenValue,\n\t\t\t}})\n\n\t\t\tv, err := PathParam[bool](c, \"key\")\n\t\t\tif tc.expectErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, tc.expectErr)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\t\t\tassert.Equal(t, tc.expect, v)\n\t\t})\n\t}\n}\n\nfunc TestPathParam_UnsupportedType(t *testing.T) {\n\tc := NewContext(nil, nil)\n\tc.SetPathValues(PathValues{{Name: \"key\", Value: \"true\"}})\n\n\tv, err := PathParam[[]bool](c, \"key\")\n\n\texpectErr := \"code=400, message=path value, err=failed to parse va", "suffix": "\n\t\texpect bool\n\t\texpectErr string\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tgivenURL: \"/?key=true\",\n\t\t\texpect: true,\n\t\t},\n\t\t{\n\t\t\tname: \"nok, non existent key\",\n\t\t\tgivenURL: \"/?different=true\",\n\t\t\texpect: false,\n\t\t\texpectErr: ErrNonExistentKey.Error(),\n\t\t", "middle": "lue, err: unsupported value type: *[]bool, field=key\"\n\tassert.EqualError(t, err, expectErr)\n\tassert.Equal(t, []bool(nil), v)\n}\n\nfunc TestQueryParam(t *testing.T) {\n\tvar testCases = []struct {\n\t\tname string\n\t\tgivenURL string", "meta": {"filepath": "binder_generic_test.go", "language": "go", "file_size": 37215, "cut_index": 2151, "middle_length": 229}}
{"prefix": "nse-Identifier: MIT\n// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors\n\npackage echo\n\nimport \"errors\"\n\n// ErrNonExistentKey is error that is returned when key does not exist\nvar ErrNonExistentKey = errors.New(\"non existent key\")\n\n// ErrInvalidKeyType is error that is returned when the value is not castable to expected type.\nvar ErrInvalidKeyType = errors.New(\"invalid key type\")\n\n// ContextGet retrieves a value from the context store or ErrNonExistentKey error the key is missing.\n// Returns", "suffix": "ErrNonExistentKey\n\t}\n\n\ttyped, ok := val.(T)\n\tif !ok {\n\t\tvar zero T\n\t\treturn zero, ErrInvalidKeyType\n\t}\n\n\treturn typed, nil\n}\n\n// ContextGetOr retrieves a value from the context store or returns a default value when the key\n// is missing. Returns ErrInvalid", "middle": " ErrInvalidKeyType error if the value is not castable to type T.\nfunc ContextGet[T any](c *Context, key string) (T, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tval, ok := c.store[key]\n\tif !ok {\n\t\tvar zero T\n\t\treturn zero, ", "meta": {"filepath": "context_generic.go", "language": "go", "file_size": 1261, "cut_index": 524, "middle_length": 229}}
{"prefix": "ent = \"invalid content\"\n\tuserJSONInvalidType = `{\"id\":\"1\",\"name\":\"Jon Snow\"}`\n\tuserXMLConvertNumberError = `Number oneJon Snow`\n\tuserXMLUnsupportedTypeError = `<>Number one>Jon Snow`\n)\n\nconst userJSONPretty = `{\n \"id\": 1,\n \"name\": \"Jon Snow\"\n}`\n\nconst userXMLPretty = `\n 1\n Jon Snow\n`\n\nvar dummyQuery = url.Values{\"dummy\": []string{\"useless\"}}\n\nfunc TestEcho(t *testing.T) {\n\te := New()\n", "suffix": "sInternalServerError, rec.Code)\n}\n\nfunc TestNewWithConfig(t *testing.T) {\n\te := NewWithConfig(Config{})\n\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\trec := httptest.NewRecorder()\n\n\te.GET(\"/\", func(c *Context) error {\n\t\treturn c.String(http.Status", "middle": "\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\n\t// Router\n\tassert.NotNil(t, e.Router())\n\n\te.HTTPErrorHandler(c, errors.New(\"error\"))\n\n\tassert.Equal(t, http.Statu", "meta": {"filepath": "echo_test.go", "language": "go", "file_size": 33660, "cut_index": 1331, "middle_length": 229}}
{"prefix": "package echo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestHTTPError_StatusCode(t *testing.T) {\n\tvar err error = &HTTPError{Code: http.StatusBadRequest, Message: \"my error message\"}\n\n\tcode := 0\n\tvar sc HTTPStatusCoder\n\tif errors.As(err, &sc) {\n\t\tcode = sc.StatusCode()\n\t}\n\tassert.Equal(t, http.StatusBadRequest, code)\n}\n\nfunc TestHTTPError_Error(t *testing.T) {\n\tvar testCases = []struct {\n\t\tname string\n\t\terror error\n\t\texpect string\n\t}{\n\t\t{\n\t\t\tname: \"", "suffix": "essage\"},\n\t\t\texpect: \"code=400, message=my error message\",\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tassert.Equal(t, tc.expect, tc.error.Error())\n\t\t})\n\t}\n}\n\nfunc TestHTTPError_WrapUnwrap(t *testing.T) {\n\terr := &HTTPE", "middle": "ok, without message\",\n\t\t\terror: &HTTPError{Code: http.StatusBadRequest},\n\t\t\texpect: \"code=400, message=Bad Request\",\n\t\t},\n\t\t{\n\t\t\tname: \"ok, with message\",\n\t\t\terror: &HTTPError{Code: http.StatusBadRequest, Message: \"my error m", "meta": {"filepath": "httperror_test.go", "language": "go", "file_size": 4615, "cut_index": 614, "middle_length": 229}}
{"prefix": "package echo\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestResponse(t *testing.T) {\n\te := New()\n\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tres := NewResponse(rec, e.Logger)\n\n\t// Before\n\tres.Before(func() {\n\t\tc.Response().Header().Set(HeaderServer, \"echo\")\n\t})\n\t// After\n\tres.After(func() {\n\t\tc.Response().Header().Set(HeaderXFrameOptions, \"DENY\")\n\t})\n\tres.Write([]byte(\"test\"))\n\tas", "suffix": "\tres := NewResponse(rec, e.Logger)\n\n\tres.Write([]byte(\"test\"))\n\tassert.Equal(t, http.StatusOK, rec.Code)\n}\n\nfunc TestResponse_Write_UsesSetResponseCode(t *testing.T) {\n\te := New()\n\trec := httptest.NewRecorder()\n\tres := NewResponse(rec, e.Logger)\n\n\tres.Stat", "middle": "sert.Equal(t, \"echo\", rec.Header().Get(HeaderServer))\n\tassert.Equal(t, \"DENY\", rec.Header().Get(HeaderXFrameOptions))\n}\n\nfunc TestResponse_Write_FallsBackToDefaultStatus(t *testing.T) {\n\te := New()\n\trec := httptest.NewRecorder()\n", "meta": {"filepath": "response_test.go", "language": "go", "file_size": 3102, "cut_index": 614, "middle_length": 229}}
{"prefix": "tx stdContext.Context, e *Echo) (string, error) {\n\taddrChan := make(chan string)\n\terrCh := make(chan error)\n\n\tgo func() {\n\t\terrCh <- (&StartConfig{\n\t\t\tAddress: \":0\",\n\t\t\tGracefulTimeout: 100 * time.Millisecond,\n\t\t\tListenerAddrFunc: func(addr net.Addr) {\n\t\t\t\taddrChan <- addr.String()\n\t\t\t},\n\t\t}).Start(ctx, e)\n\t}()\n\n\treturn waitForServerStart(addrChan, errCh)\n}\n\nfunc waitForServerStart(addrChan <-chan string, errCh <-chan error) (string, error) {\n\twaitCtx, cancel := stdContext.WithTimeout(stdContext.Bac", "suffix": "== http.ErrServerClosed { // was closed normally before listener callback was called. should not be possible\n\t\t\t\treturn \"\", nil\n\t\t\t}\n\t\t\t// failed to start and we did not manage to get even listener part.\n\t\t\treturn \"\", err\n\t\t}\n\t}\n}\n\nfunc doGet(url string) (", "middle": "kground(), 200*time.Millisecond)\n\tdefer cancel()\n\n\t// wait for addr to arrive\n\tfor {\n\t\tselect {\n\t\tcase <-waitCtx.Done():\n\t\t\treturn \"\", waitCtx.Err()\n\t\tcase addr := <-addrChan:\n\t\t\treturn addr, nil\n\t\tcase err := <-errCh:\n\t\t\tif err ", "meta": {"filepath": "server_test.go", "language": "go", "file_size": 16424, "cut_index": 921, "middle_length": 229}}
{"prefix": "o.Context) error {\n\t\tc.Response().Write([]byte(\"test\")) // For Content-Type sniffing\n\t\treturn nil\n\t})\n\n\te := echo.New()\n\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\n\terr := h(c)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, \"test\", rec.Body.String())\n}\n\nfunc TestMustGzipWithConfig_panics(t *testing.T) {\n\tassert.Panics(t, func() {\n\t\tGzipWithConfig(GzipConfig{Level: 999})\n\t})\n}\n\nfunc TestGzip_AcceptEncodingHeader(t *testing.T) {\n\th := Gzip()(fu", "suffix": "pScheme)\n\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\n\terr := h(c)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, gzipScheme, rec.Header().Get(echo.HeaderContentEncoding))\n\tassert.Contains(t, rec.Header().Get(echo.HeaderContentType), echo.MIMET", "middle": "nc(c *echo.Context) error {\n\t\tc.Response().Write([]byte(\"test\")) // For Content-Type sniffing\n\t\treturn nil\n\t})\n\n\te := echo.New()\n\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\treq.Header.Set(echo.HeaderAcceptEncoding, gzi", "meta": {"filepath": "middleware/compress_test.go", "language": "go", "file_size": 10852, "cut_index": 921, "middle_length": 229}}
{"prefix": "equest func() *http.Request\n\t\tgivenPathValues echo.PathValues\n\t\twhenLookups string\n\t\twhenLimit uint\n\t\texpectValues []string\n\t\texpectSource ExtractorSource\n\t\texpectCreateError string\n\t\texpectError string\n\t}{\n\t\t{\n\t\t\tname: \"ok, header\",\n\t\t\tgivenRequest: func() *http.Request {\n\t\t\t\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\t\t\t\treq.Header.Set(echo.HeaderAuthorization, \"Bearer token\")\n\t\t\t\treturn req\n\t\t\t},\n\t\t\twhenLookups: \"header:Authorization:Bearer \",\n\t\t\texpectValu", "suffix": "hodPost, \"/\", strings.NewReader(f.Encode()))\n\t\t\t\treq.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm)\n\t\t\t\treturn req\n\t\t\t},\n\t\t\twhenLookups: \"form:name\",\n\t\t\texpectValues: []string{\"Jon Snow\"},\n\t\t\texpectSource: ExtractorSourceForm,\n\t\t},\n\t\t{\n\t\t\tna", "middle": "es: []string{\"token\"},\n\t\t\texpectSource: ExtractorSourceHeader,\n\t\t},\n\t\t{\n\t\t\tname: \"ok, form\",\n\t\t\tgivenRequest: func() *http.Request {\n\t\t\t\tf := make(url.Values)\n\t\t\t\tf.Set(\"name\", \"Jon Snow\")\n\n\t\t\t\treq := httptest.NewRequest(http.Met", "meta": {"filepath": "middleware/extractor_test.go", "language": "go", "file_size": 17007, "cut_index": 921, "middle_length": 229}}
{"prefix": "htText: © 2015 LabStack LLC and Echo contributors\n\npackage middleware\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"runtime\"\n\n\t\"github.com/labstack/echo/v5\"\n)\n\n// RecoverConfig defines the config for Recover middleware.\ntype RecoverConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// Size of the stack to be printed.\n\t// Optional. Default value 4KB.\n\tStackSize int\n\n\t// DisableStackAll disables formatting stack traces of all other goroutines\n\t// into buffer after the trace for the current", "suffix": "cover middleware config.\nvar DefaultRecoverConfig = RecoverConfig{\n\tSkipper: DefaultSkipper,\n\tStackSize: 4 << 10, // 4 KB\n\tDisableStackAll: false,\n\tDisablePrintStack: false,\n}\n\n// Recover returns a middleware which recovers from panics ", "middle": " goroutine.\n\t// Optional. Default value false.\n\tDisableStackAll bool\n\n\t// DisablePrintStack disables printing stack trace.\n\t// Optional. Default value as false.\n\tDisablePrintStack bool\n}\n\n// DefaultRecoverConfig is the default Re", "meta": {"filepath": "middleware/recover.go", "language": "go", "file_size": 2789, "cut_index": 563, "middle_length": 229}}
{"prefix": "d do not affect which route handler is matched\n\te.Use(RewriteWithConfig(RewriteConfig{\n\t\tRules: map[string]string{\n\t\t\t\"/old\": \"/new\",\n\t\t\t\"/api/*\": \"/$1\",\n\t\t\t\"/js/*\": \"/public/javascripts/$1\",\n\t\t\t\"/users/*/orders/*\": \"/user/$1/order/$2\",\n\t\t},\n\t}))\n\te.GET(\"/public/*\", func(c *echo.Context) error {\n\t\treturn c.String(http.StatusOK, c.Param(\"*\"))\n\t})\n\te.GET(\"/*\", func(c *echo.Context) error {\n\t\treturn c.String(http.StatusOK, c.Param(\"*\"))\n\t})\n\n\tvar testCases = []struct {\n\t\twhe", "suffix": "ers\",\n\t\t\texpectRequestRawPath: \"\",\n\t\t},\n\t\t{\n\t\t\twhenPath: \"/js/main.js\",\n\t\t\texpectRoutePath: \"js/main.js\",\n\t\t\texpectRequestPath: \"/public/javascripts/main.js\",\n\t\t\texpectRequestRawPath: \"\",\n\t\t},\n\t\t{\n\t\t\twhenPath: \"/users/jack/o", "middle": "nPath string\n\t\texpectRoutePath string\n\t\texpectRequestPath string\n\t\texpectRequestRawPath string\n\t}{\n\t\t{\n\t\t\twhenPath: \"/api/users\",\n\t\t\texpectRoutePath: \"api/users\",\n\t\t\texpectRequestPath: \"/us", "meta": {"filepath": "middleware/rewrite_test.go", "language": "go", "file_size": 9227, "cut_index": 921, "middle_length": 229}}
{"prefix": "trI64\" form:\"PtrI64\"`\n\tPtrI *int `json:\"PtrI\" form:\"PtrI\"`\n\tPtrI8 *int8 `json:\"PtrI8\" form:\"PtrI8\"`\n\tPtrF64 *float64 `json:\"PtrF64\" form:\"PtrF64\"`\n\tPtrUI8 *uint8 `json:\"PtrUI8\" form:\"PtrUI8\"`\n\tPtrUI64 *uint64 `json:\"PtrUI64\" form:\"PtrUI64\"`\n\tPtrUI16 *uint16 `json:\"PtrUI16\" form:\"PtrUI16\"`\n\tPtrS *string `json:\"PtrS\" form:\"PtrS\"`\n\tPtrUI32 *uint32 `json:\"PtrUI32\" form:\"PtrUI32\"`\n\tS string `json:\"S\" form:\"S\"`\n\tcantSet strin", "suffix": " `json:\"UI64\" form:\"UI64\"`\n\tUI uint `json:\"UI\" form:\"UI\"`\n\tI64 int64 `json:\"I64\" form:\"I64\"`\n\tF32 float32 `json:\"F32\" form:\"F32\"`\n\tUI32 uint32 `json:\"UI32\" form:\"UI32\"`\n\tI32 int32 `json", "middle": "g\n\tDoesntExist string `json:\"DoesntExist\" form:\"DoesntExist\"`\n\tSA StringArray `json:\"SA\" form:\"SA\"`\n\tF64 float64 `json:\"F64\" form:\"F64\"`\n\tI int `json:\"I\" form:\"I\"`\n\tUI64 uint64 ", "meta": {"filepath": "bind_test.go", "language": "go", "file_size": 53023, "cut_index": 2151, "middle_length": 229}}
{"prefix": "// run tests as external package to get real feel for API\npackage echo_test\n\nimport (\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\n\t\"github.com/labstack/echo/v5\"\n)\n\nfunc ExampleValueBinder_BindErrors() {\n\t// example route function that binds query params to different destinations and returns all bind errors in one go\n\trouteFunc := func(c *echo.Context) error {\n\t\tvar opts struct {\n\t\t\tIDs []int64\n\t\t\tActive bool\n\t\t}\n\t\tlength := int64(50) // default length is 50\n\n\t\tb := echo.QueryParams", "suffix": "rror)\n\t\t\t\tlog.Printf(\"in case you want to access what field: %s values: %v failed\", bErr.Field, bErr.Values)\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"%v fields failed to bind\", len(errs))\n\t\t}\n\t\tfmt.Printf(\"active = %v, length = %v, ids = %v\", opts.Active, length, opts.I", "middle": "Binder(c)\n\n\t\terrs := b.Int64(\"length\", &length).\n\t\t\tInt64s(\"ids\", &opts.IDs).\n\t\t\tBool(\"active\", &opts.Active).\n\t\t\tBindErrors() // returns all errors\n\t\tif errs != nil {\n\t\t\tfor _, err := range errs {\n\t\t\t\tbErr := err.(*echo.BindingE", "meta": {"filepath": "binder_external_test.go", "language": "go", "file_size": 3889, "cut_index": 614, "middle_length": 229}}
{"prefix": "g time.Time values\ntype TimeOpts struct {\n\t// Layout specifies the format for parsing time values in request parameters.\n\t// It can be a standard Go time layout string or one of the special Unix time layouts.\n\t//\n\t// Parsing layout defaults to: echo.TimeLayout(time.RFC3339Nano)\n\t// - To convert to custom layout use `echo.TimeLayout(\"2006-01-02\")`\n\t// - To convert unix timestamp (integer) to time.Time use `echo.TimeLayoutUnixTime`\n\t// - To convert unix timestamp in milliseconds to time.Time use `echo.TimeLay", "suffix": " timezone information to set output time in given location.\n\t// Defaults to time.UTC\n\tParseInLocation *time.Location\n\n\t// ToInLocation is location to which parsed time is converted to after parsing.\n\t// The parsed time will be converted using time.In(ToInL", "middle": "outUnixTimeMilli`\n\t// - To convert unix timestamp in nanoseconds to time.Time use `echo.TimeLayoutUnixTimeNano`\n\tLayout TimeLayout\n\n\t// ParseInLocation is location used with time.ParseInLocation for layout that do not contain\n\t//", "meta": {"filepath": "binder_generic.go", "language": "go", "file_size": 16934, "cut_index": 921, "middle_length": 229}}
{"prefix": "c := createTestContext(tc.whenURL, nil, map[string]string{\"id\": \"999\"})\n\t\t\tb := QueryParamsBinder(c).FailFast(tc.givenFailFast)\n\t\t\tid := int64(99)\n\t\t\tnr := int64(88)\n\t\t\terrs := b.Int64(\"id\", &id).\n\t\t\t\tInt64(\"nr\", &nr).\n\t\t\t\tBindErrors()\n\n\t\t\tassert.Len(t, errs, len(tc.expectError))\n\t\t\tfor _, err := range errs {\n\t\t\t\tassert.Contains(t, tc.expectError, err.Error())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFormFieldBinder(t *testing.T) {\n\te := New()\n\tbody := `texta=foo&slice=5`\n\treq := httptest.NewRequest(http.MethodPost, \"/api/", "suffix": "req, rec)\n\n\tb := FormFieldBinder(c)\n\n\tvar texta string\n\tid := int64(99)\n\tnr := int64(88)\n\tvar slice = make([]int64, 0)\n\tvar notExisting = make([]int64, 0)\n\terr := b.\n\t\tInt64s(\"slice\", &slice).\n\t\tInt64(\"id\", &id).\n\t\tInt64(\"nr\", &nr).\n\t\tString(\"texta\", &text", "middle": "search?id=1&nr=2&slice=3&slice=4\", strings.NewReader(body))\n\treq.Header.Set(HeaderContentLength, strconv.Itoa(len(body)))\n\treq.Header.Set(HeaderContentType, MIMEApplicationForm)\n\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(", "meta": {"filepath": "binder_test.go", "language": "go", "file_size": 95170, "cut_index": 3790, "middle_length": 229}}
{"prefix": "emory int64 = 32 << 20 // 32 MB\n\tindexPage = \"index.html\"\n)\n\n// Context represents the context of the current HTTP request. It holds request and\n// response objects, path, path parameters, data and registered handler.\ntype Context struct {\n\trequest *http.Request\n\torgResponse *Response\n\tresponse http.ResponseWriter\n\tquery url.Values\n\n\t// formParseMaxMemory is used for http.Request.ParseMultipartForm\n\tformParseMaxMemory int64\n\n\troute *RouteInfo\n\tpathValues *PathValues\n\n\tstore map[", "suffix": "nyway\n// these arguments are useful when creating context for tests and cases like that.\nfunc NewContext(r *http.Request, w http.ResponseWriter, opts ...any) *Context {\n\tvar e *Echo\n\tfor _, opt := range opts {\n\t\tswitch v := opt.(type) {\n\t\tcase *Echo:\n\t\t\te ", "middle": "string]any\n\techo *Echo\n\tlogger *slog.Logger\n\n\tpath string\n\tlock sync.RWMutex\n}\n\n// NewContext returns a new Context instance.\n//\n// Note: request,response and e can be left to nil as Echo.ServeHTTP will call c.Reset(req,resp) a", "meta": {"filepath": "context.go", "language": "go", "file_size": 21433, "cut_index": 1331, "middle_length": 229}}
{"prefix": "nse-Identifier: MIT\n// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors\n\npackage echo\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestContextGetOK(t *testing.T) {\n\tc := NewContext(nil, nil)\n\n\tc.Set(\"key\", int64(123))\n\n\tv, err := ContextGet[int64](c, \"key\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, int64(123), v)\n}\n\nfunc TestContextGetNonExistentKey(t *testing.T) {\n\tc := NewContext(nil, nil)\n\n\tc.Set(\"key\", int64(123))\n\n\tv, err := ContextGet[int64](c, \"nope\")\n\tassert.Er", "suffix": " ErrInvalidKeyType)\n\tassert.Equal(t, false, v)\n}\n\nfunc TestContextGetOrOK(t *testing.T) {\n\tc := NewContext(nil, nil)\n\n\tc.Set(\"key\", int64(123))\n\n\tv, err := ContextGetOr[int64](c, \"key\", 999)\n\tassert.NoError(t, err)\n\tassert.Equal(t, int64(123), v)\n}\n\nfunc T", "middle": "rorIs(t, err, ErrNonExistentKey)\n\tassert.Equal(t, int64(0), v)\n}\n\nfunc TestContextGetInvalidCast(t *testing.T) {\n\tc := NewContext(nil, nil)\n\n\tc.Set(\"key\", int64(123))\n\n\tv, err := ContextGet[bool](c, \"key\")\n\tassert.ErrorIs(t, err,", "meta": {"filepath": "context_generic_test.go", "language": "go", "file_size": 1455, "cut_index": 524, "middle_length": 229}}
{"prefix": "wardedFor: []string{\"127.0.0.1, 127.0.1.1, \"}},\n\t}}\n\tfor i := 0; i < b.N; i++ {\n\t\tc.RealIP()\n\t}\n}\n\nfunc (t *Template) Render(c *Context, w io.Writer, name string, data any) error {\n\treturn t.templates.ExecuteTemplate(w, name, data)\n}\n\nfunc TestContextEcho(t *testing.T) {\n\te := New()\n\treq := httptest.NewRequest(http.MethodPost, \"/\", strings.NewReader(userJSON))\n\trec := httptest.NewRecorder()\n\n\tc := e.NewContext(req, rec)\n\n\tassert.Equal(t, e, c.Echo())\n}\n\nfunc TestContextRequest(t *testing.T) {\n\te := New()\n\tr", "suffix": "nse(t *testing.T) {\n\te := New()\n\treq := httptest.NewRequest(http.MethodPost, \"/\", strings.NewReader(userJSON))\n\trec := httptest.NewRecorder()\n\n\tc := e.NewContext(req, rec)\n\n\tassert.NotNil(t, c.Response())\n}\n\nfunc TestContextRenderTemplate(t *testing.T) {\n\t", "middle": "eq := httptest.NewRequest(http.MethodPost, \"/\", strings.NewReader(userJSON))\n\trec := httptest.NewRecorder()\n\n\tc := e.NewContext(req, rec)\n\n\tassert.NotNil(t, c.Request())\n\tassert.Equal(t, req, c.Request())\n}\n\nfunc TestContextRespo", "meta": {"filepath": "context_test.go", "language": "go", "file_size": 39529, "cut_index": 2151, "middle_length": 229}}
{"prefix": "\"errors\"\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"syscall\"\n)\n\n// Echo is the top-level framework instance.\n//\n// Goroutine safety: Do not mutate Echo instance fields after server has started. Accessing these\n// fields from handlers/middlewares and changing field values at the same time leads to data-races.\n// Same rule applies to adding new routes after server has been started - Adding a route is not Goroutine safe action.\ntyp", "suffix": ".Open() already assumes that file names are relative to FS root path and considers name with prefix `/` as invalid\n\t// so if you have `fs := os.DirFS(\"/tmp\")` and you try to `fs.Open(\"/tmp/file.txt\")` it will fail, but \"file.txt\"\n\t// would succeed. `echo.N", "middle": "e Echo struct {\n\tserveHTTPFunc func(http.ResponseWriter, *http.Request)\n\n\tBinder Binder\n\n\t// Filesystem is the file system used for serving static files. Defaults to the current working directory (os.Getwd()).\n\t//\n\t// Note: fs.FS", "meta": {"filepath": "echo.go", "language": "go", "file_size": 32080, "cut_index": 1331, "middle_length": 229}}
{"prefix": "It can be used for inner\n// routes that share a common middleware or functionality that should be separate\n// from the parent echo instance while still inheriting from it.\ntype Group struct {\n\techo *Echo\n\tprefix string\n\tmiddleware []MiddlewareFunc\n}\n\n// Use implements `Echo#Use()` for sub-routes within the Group.\n// Group middlewares are not executed on request when there is no matching route found.\nfunc (g *Group) Use(middleware ...MiddlewareFunc) {\n\tg.middleware = append(g.middleware, middleware", "suffix": ")\n}\n\n// DELETE implements `Echo#DELETE()` for sub-routes within the Group. Panics on error.\nfunc (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo {\n\treturn g.Add(http.MethodDelete, path, h, m...)\n}\n\n// GET implements `Echo#GET()", "middle": "...)\n}\n\n// CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. Panics on error.\nfunc (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfo {\n\treturn g.Add(http.MethodConnect, path, h, m...", "meta": {"filepath": "group.go", "language": "go", "file_size": 6999, "cut_index": 716, "middle_length": 229}}
{"prefix": " code by implementing HTTPStatusCoder interface\nvar (\n\tErrBadRequest = &httpError{http.StatusBadRequest} // 400\n\tErrUnauthorized = &httpError{http.StatusUnauthorized} // 401\n\tErrForbidden = &httpError{http.StatusForbidden} // 403\n\tErrNotFound = &httpError{http.StatusNotFound} // 404\n\tErrMethodNotAllowed = &httpError{http.StatusMethodNotAllowed} // 405\n\tErrRequestTimeout ", "suffix": "\n\tErrTooManyRequests = &httpError{http.StatusTooManyRequests} // 429\n\tErrInternalServerError = &httpError{http.StatusInternalServerError} // 500\n\tErrBadGateway = &httpError{http.StatusBadGateway} // 5", "middle": " = &httpError{http.StatusRequestTimeout} // 408\n\tErrStatusRequestEntityTooLarge = &httpError{http.StatusRequestEntityTooLarge} // 413\n\tErrUnsupportedMediaType = &httpError{http.StatusUnsupportedMediaType} // 415", "meta": {"filepath": "httperror.go", "language": "go", "file_size": 5278, "cut_index": 716, "middle_length": 229}}
{"prefix": "SPDX-License-Identifier: MIT\n// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors\n\n// run tests as external package to get real feel for API\npackage echo_test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/labstack/echo/v5\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n)\n\nfunc ExampleDefaultHTTPErrorHandler() {\n\te := echo.New()\n\te.GET(\"/api/endpoint\", func(c *echo.Context) error {\n\t\treturn &apiError{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tBody: map[string]any{\"message\": \"custom error\"},\n\t\t}\n\t})\n\n\treq := http", "suffix": "pe apiError struct {\n\tCode int\n\tBody any\n}\n\nfunc (e *apiError) StatusCode() int {\n\treturn e.Code\n}\n\nfunc (e *apiError) MarshalJSON() ([]byte, error) {\n\ttype body struct {\n\t\tError any `json:\"error\"`\n\t}\n\treturn json.Marshal(body{Error: e.Body})\n}\n\nfunc (e *a", "middle": "test.NewRequest(http.MethodGet, \"/api/endpoint?err=1\", nil)\n\tresp := httptest.NewRecorder()\n\n\te.ServeHTTP(resp, req)\n\n\tfmt.Printf(\"%d %s\", resp.Code, resp.Body.String())\n\n\t// Output: 400 {\"error\":{\"message\":\"custom error\"}}\n}\n\nty", "meta": {"filepath": "httperror_external_test.go", "language": "go", "file_size": 1061, "cut_index": 515, "middle_length": 229}}
{"prefix": "utesWillNotExecuteMiddlewareFor404(t *testing.T) {\n\te := New()\n\n\tcalled := false\n\tmw := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c *Context) error {\n\t\t\tcalled = true\n\t\t\treturn c.NoContent(http.StatusTeapot)\n\t\t}\n\t}\n\t// even though group has middleware and routes when we have no match on some route the middlewares for that\n\t// group will not be executed\n\tg := e.Group(\"/group\", mw)\n\tg.GET(\"/yes\", handlerFunc)\n\n\tstatus, body := request(http.MethodGet, \"/group/nope\", e)\n\tassert.Equal(t, http.StatusNotF", "suffix": "vate\", func(c *Context) error {\n\t\treturn c.String(http.StatusTeapot, \"OK\")\n\t})\n\n\tstatus, body := request(http.MethodGet, \"/api/users/activate\", e)\n\tassert.Equal(t, http.StatusTeapot, status)\n\tassert.Equal(t, `OK`, body)\n}\n\nfunc TestGroupFile(t *testing.T) ", "middle": "ound, status)\n\tassert.Equal(t, `{\"message\":\"Not Found\"}`+\"\\n\", body)\n\n\tassert.False(t, called)\n}\n\nfunc TestGroup_multiLevelGroup(t *testing.T) {\n\te := New()\n\n\tapi := e.Group(\"/api\")\n\tusers := api.Group(\"/users\")\n\tusers.GET(\"/acti", "meta": {"filepath": "group_test.go", "language": "go", "file_size": 23556, "cut_index": 1331, "middle_length": 229}}
{"prefix": "ol, auditing, geo-based access analysis and more.\nEcho provides handy method [`Context#RealIP()`](https://godoc.org/github.com/labstack/echo#Context) for that.\n\nHowever, it is not trivial to retrieve the _real_ IP address from requests especially when you put L7 proxies before the application.\nIn such situation, _real_ IP needs to be relayed on HTTP layer from proxies to your app, but you must not trust HTTP headers unconditionally.\nOtherwise, you might give someone a chance of deceiving you. **A security r", "suffix": "ow you why and how.\n\n> Note: if you don't set `Echo#IPExtractor` explicitly, Echo fallback to legacy behavior, which is not a good choice.\n\nLet's start from two questions to know the right direction:\n\n1. Do you put any HTTP (L7) proxy in front of the appli", "middle": "isk!**\n\nTo retrieve IP address reliably/securely, you must let your application be aware of the entire architecture of your infrastructure.\nIn Echo, this can be done by configuring `Echo#IPExtractor` appropriately.\nThis guides sh", "meta": {"filepath": "ip.go", "language": "go", "file_size": 11190, "cut_index": 921, "middle_length": 229}}
{"prefix": "SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors\n\npackage echo\n\nimport (\n\t\"encoding/json\"\n)\n\n// DefaultJSONSerializer implements JSON encoding using encoding/json.\ntype DefaultJSONSerializer struct{}\n\n// Serialize converts an interface into a json and writes it to the response.\n// You can optionally use the indent parameter to produce pretty JSONs.\nfunc (d DefaultJSONSerializer) Serialize(c *Context, target any, indent string) error {\n\tenc := json.NewEncoder(c.Response())\n\tif indent != \"\" {", "suffix": "arget)\n}\n\n// Deserialize reads a JSON from a request body and converts it into an interface.\nfunc (d DefaultJSONSerializer) Deserialize(c *Context, target any) error {\n\tif err := json.NewDecoder(c.Request().Body).Decode(target); err != nil {\n\t\treturn ErrBa", "middle": "\n\t\tenc.SetIndent(\"\", indent)\n\t}\n\treturn enc.Encode(t", "meta": {"filepath": "json.go", "language": "go", "file_size": 892, "cut_index": 547, "middle_length": 52}}
{"prefix": "tack LLC and Echo contributors\n\npackage echo\n\nimport \"io\"\n\n// Renderer is the interface that wraps the Render function.\ntype Renderer interface {\n\tRender(c *Context, w io.Writer, templateName string, data any) error\n}\n\n// TemplateRenderer is helper to ease creating renderers for `html/template` and `text/template` packages.\n// Example usage:\n//\n//\t\te.Renderer = &echo.TemplateRenderer{\n//\t\t\tTemplate: template.Must(template.ParseGlob(\"templates/*.html\")),\n//\t\t}\n//\n//\t e.Renderer = &echo.TemplateRenderer{\n//\t", "suffix": "e(\"Hello, {{.}}!\")),\n//\t\t}\ntype TemplateRenderer struct {\n\tTemplate interface {\n\t\tExecuteTemplate(wr io.Writer, name string, data any) error\n\t}\n}\n\n// Render renders the template with given data.\nfunc (t *TemplateRenderer) Render(c *Context, w io.Writer, na", "middle": "\t\tTemplate: template.Must(template.New(\"hello\").Pars", "meta": {"filepath": "renderer.go", "language": "go", "file_size": 972, "cut_index": 582, "middle_length": 52}}
{"prefix": "00:0000:0000:0000:0000:0103\n\t\t\t\t// Range start: \t\t2001:0db8:0000:0000:0000:0000:0000:0000\n\t\t\t\t// Range end: \t\t\t2001:0db8:0000:ffff:ffff:ffff:ffff:ffff\n\t\t\t\tTrustIPRange(mustParseCIDR(\"2001:db8::103/48\")),\n\t\t\t},\n\t\t\twhenIP: \"2001:0db8:0000:0000:0000:0000:0000:0103\",\n\t\t\texpect: true,\n\t\t},\n\t\t{\n\t\t\tname: \"ip is within trust range, trusts additional private IPV6 network\",\n\t\t\tgivenOptions: []TrustOption{\n\t\t\t\tTrustIPRange(mustParseCIDR(\"2001:db8::103/48\")),\n\t\t\t},\n\t\t\twhenIP: \"2001:0db8:0000:0000:0000:0000:0000:0103\",\n", "suffix": "\n\t\t})\n\t}\n}\n\nfunc TestTrustIPRange(t *testing.T) {\n\tvar testCases = []struct {\n\t\tname string\n\t\tgivenRange string\n\t\twhenIP string\n\t\texpect bool\n\t}{\n\t\t{\n\t\t\tname: \"ip is within trust range, IPV6 network range\",\n\t\t\t// CIDR Notation: 2001:0db8:0000", "middle": "\t\t\texpect: true,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tchecker := newIPChecker(tc.givenOptions)\n\n\t\t\tresult := checker.trust(net.ParseIP(tc.whenIP))\n\t\t\tassert.Equal(t, tc.expect, result)", "meta": {"filepath": "ip_test.go", "language": "go", "file_size": 23690, "cut_index": 1331, "middle_length": 229}}
{"prefix": "n http.ResponseWriter and implements its interface to be used\n// by an HTTP handler to construct an HTTP response.\n// See: https://golang.org/pkg/net/http/#ResponseWriter\ntype Response struct {\n\thttp.ResponseWriter\n\tlogger *slog.Logger\n\t// beforeFuncs are functions that are called just before the response (status) is written. Happens only once, during WriteHeader call.\n\tbeforeFuncs []func()\n\t// afterFuncs are functions that are called just after the response is written. During every `Write` method call.\n\taf", "suffix": "ter: w, logger: logger}\n}\n\n// Before registers a function which is called just before the response (status) is written.\nfunc (r *Response) Before(fn func()) {\n\tr.beforeFuncs = append(r.beforeFuncs, fn)\n}\n\n// After registers a function which is called just ", "middle": "terFuncs []func()\n\tStatus int\n\tSize int64\n\tCommitted bool\n}\n\n// NewResponse creates a new instance of Response.\nfunc NewResponse(w http.ResponseWriter, logger *slog.Logger) (r *Response) {\n\treturn &Response{ResponseWri", "meta": {"filepath": "response.go", "language": "go", "file_size": 5614, "cut_index": 716, "middle_length": 229}}
{"prefix": "htText: © 2015 LabStack LLC and Echo contributors\n\npackage echo\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"testing\"\n)\n\n// Note this test is deliberately simple as there's not a lot to test.\n// Just need to ensure it writes JSONs. The heavy work is done by the context methods.\nfunc TestDefaultJSONCodec_Encode(t *testing.T) {\n\te := New()\n\treq := httptest.NewRequest(http.MethodPost, \"/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\n\t// Ech", "suffix": "e(c, user{ID: 1, Name: \"Jon Snow\"}, \"\")\n\tif assert.NoError(t, err) {\n\t\tassert.Equal(t, userJSON+\"\\n\", rec.Body.String())\n\t}\n\n\treq = httptest.NewRequest(http.MethodPost, \"/\", nil)\n\trec = httptest.NewRecorder()\n\tc = e.NewContext(req, rec)\n\terr = enc.Serializ", "middle": "o\n\tassert.Equal(t, e, c.Echo())\n\n\t// Request\n\tassert.NotNil(t, c.Request())\n\n\t// Response\n\tassert.NotNil(t, c.Response())\n\n\t//--------\n\t// Default JSON encoder\n\t//--------\n\n\tenc := new(DefaultJSONSerializer)\n\n\terr := enc.Serializ", "meta": {"filepath": "json_test.go", "language": "go", "file_size": 2742, "cut_index": 563, "middle_length": 229}}
{"prefix": "package echo\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"runtime\"\n)\n\n// Route contains information to adding/registering new route with the router.\n// Method+Path pair uniquely identifies the Route. It is mandatory to provide Method+Path+Handler fields.\ntype Route struct {\n\tMethod string\n\tPath string\n\tName string\n\tHandler HandlerFunc\n\tMiddlewares []MiddlewareFunc\n}\n\n// ToRouteInfo converts Route to RouteInfo\nfunc (r Route) ToRouteInfo(params []string) RouteInfo {\n\tname := r.Name\n", "suffix": "dded group prefix and group middlewares it is grouped to.\nfunc (r Route) WithPrefix(pathPrefix string, middlewares []MiddlewareFunc) Route {\n\tr.Path = pathPrefix + r.Path\n\n\tif len(middlewares) > 0 {\n\t\tm := make([]MiddlewareFunc, 0, len(middlewares)+len(r.M", "middle": "\tif name == \"\" {\n\t\tname = r.Method + \":\" + r.Path\n\t}\n\n\treturn RouteInfo{\n\t\tMethod: r.Method,\n\t\tPath: r.Path,\n\t\tParameters: append([]string(nil), params...),\n\t\tName: name,\n\t}\n}\n\n// WithPrefix recreates Route with a", "meta": {"filepath": "route.go", "language": "go", "file_size": 5051, "cut_index": 614, "middle_length": 229}}
{"prefix": "with the Router and returns registered RouteInfo.\n\t//\n\t// Router may change Route.Path value in returned RouteInfo.Path.\n\t// Router generates RouteInfo.Parameters values from Route.Path.\n\t// Router generates RouteInfo.Name value if it is not provided.\n\tAdd(routable Route) (RouteInfo, error)\n\n\t// Remove removes route from the Router.\n\t//\n\t// Router may choose not to implement this method.\n\tRemove(method string, path string) error\n\n\t// Routes returns information about all registered routes\n\tRoutes() Routes\n\n\t", "suffix": "\n\t// handler function.\n\t//\n\t// Router must populate Context during Router.Route call with:\n\t// - Context.InitializeRoute() (IMPORTANT! to reduce allocations use same slice that c.PathValues() returns)\n\t// - optionally can set additional information to Cont", "middle": "// Route searches Router for matching route and applies it to the given context. In case when no matching method\n\t// was not found (405) or no matching route exists for path (404), router will return its implementation of 405/404", "meta": {"filepath": "router.go", "language": "go", "file_size": 31612, "cut_index": 1331, "middle_length": 229}}
{"prefix": "th: \"/initial1\",\n\t\tHandler: handlerFunc,\n\t})\n\tassert.NoError(t, err)\n\tassert.Equal(t, len(router.Routes()), 1)\n\n\terr = router.Remove(http.MethodGet, \"/initial1\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, len(router.Routes()), 0)\n}\n\nfunc TestConcurrentRouter_ConcurrentReads(t *testing.T) {\n\trouter := NewConcurrentRouter(NewRouter(RouterConfig{}))\n\n\ttestPaths := []string{\"/route1\", \"/route2\", \"/route3\", \"/route4\", \"/route5\"}\n\tfor _, path := range testPaths {\n\t\t_, err := router.Add(Route{\n\t\t\tMethod: http.Me", "suffix": "Int64\n\n\tnumGoroutines := 10\n\trouteCallsPerGoroutine := 50\n\troutesCallsPerGoroutine := 20\n\n\tfor i := range numGoroutines {\n\t\twg.Add(1)\n\t\tgo func(goroutineID int) {\n\t\t\tdefer wg.Done()\n\n\t\t\t// Call Route() 50 times\n\t\t\tfor j := range routeCallsPerGoroutine {\n\t\t", "middle": "thodGet,\n\t\t\tPath: path,\n\t\t\tHandler: handlerFunc,\n\t\t})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\t// Launch 10 goroutines for concurrent reads\n\tvar wg sync.WaitGroup\n\tvar routeCallCount atomic.Int64\n\tvar routesCallCount atomic.", "meta": {"filepath": "router_concurrent_test.go", "language": "go", "file_size": 9843, "cut_index": 921, "middle_length": 229}}
{"prefix": "/gopher/bumper320x180.png\", \"\"},\n\t\t{\"GET\", \"/gopher/bumper480x270.png\", \"\"},\n\t\t{\"GET\", \"/gopher/bumper640x360.png\", \"\"},\n\t\t{\"GET\", \"/gopher/doc.png\", \"\"},\n\t\t{\"GET\", \"/gopher/frontpage.png\", \"\"},\n\t\t{\"GET\", \"/gopher/gopherbw.png\", \"\"},\n\t\t{\"GET\", \"/gopher/gophercolor.png\", \"\"},\n\t\t{\"GET\", \"/gopher/gophercolor16x16.png\", \"\"},\n\t\t{\"GET\", \"/gopher/help.png\", \"\"},\n\t\t{\"GET\", \"/gopher/pkg.png\", \"\"},\n\t\t{\"GET\", \"/gopher/project.png\", \"\"},\n\t\t{\"GET\", \"/gopher/ref.png\", \"\"},\n\t\t{\"GET\", \"/gopher/run.png\", \"\"},\n\t\t{\"GET\", \"/go", "suffix": "pherrunning.jpg\", \"\"},\n\t\t{\"GET\", \"/gopher/pencil/gopherswim.jpg\", \"\"},\n\t\t{\"GET\", \"/gopher/pencil/gopherswrench.jpg\", \"\"},\n\t\t{\"GET\", \"/play/\", \"\"},\n\t\t{\"GET\", \"/play/fib.go\", \"\"},\n\t\t{\"GET\", \"/play/hello.go\", \"\"},\n\t\t{\"GET\", \"/play/life.go\", \"\"},\n\t\t{\"GET\", \"/p", "middle": "pher/talks.png\", \"\"},\n\t\t{\"GET\", \"/gopher/pencil/\", \"\"},\n\t\t{\"GET\", \"/gopher/pencil/gopherhat.jpg\", \"\"},\n\t\t{\"GET\", \"/gopher/pencil/gopherhelmet.jpg\", \"\"},\n\t\t{\"GET\", \"/gopher/pencil/gophermega.jpg\", \"\"},\n\t\t{\"GET\", \"/gopher/pencil/go", "meta": {"filepath": "router_test.go", "language": "go", "file_size": 105029, "cut_index": 3790, "middle_length": 229}}
{"prefix": "c(c *Context) error {\n\t\treturn nil\n\t}\n\n\ttmp := NameStruct{}\n\n\tvar testCases = []struct {\n\t\tname string\n\t\twhenHandlerFunc HandlerFunc\n\t\texpect string\n\t}{\n\t\t{\n\t\t\tname: \"ok, func as anonymous func\",\n\t\t\twhenHandlerFunc: func(c *Context) error {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\texpect: \"github.com/labstack/echo/v5.TestHandlerName.func2\",\n\t\t},\n\t\t{\n\t\t\tname: \"ok, func as named package variable\",\n\t\t\twhenHandlerFunc: myNamedHandler,\n\t\t\texpect: \"github.com/labstack/echo/v5.init.func4\",\n\t", "suffix": "d\",\n\t\t\twhenHandlerFunc: tmp.getUsers,\n\t\t\texpect: \"github.com/labstack/echo/v5.(*NameStruct).getUsers-fm\",\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tname := HandlerName(tc.whenHandlerFunc)\n\t\t\tassert.Equal(t, ", "middle": "\t},\n\t\t{\n\t\t\tname: \"ok, func as named function variable\",\n\t\t\twhenHandlerFunc: myNameFuncVar,\n\t\t\texpect: \"github.com/labstack/echo/v5.TestHandlerName.func1\",\n\t\t},\n\t\t{\n\t\t\tname: \"ok, func as struct metho", "meta": {"filepath": "route_test.go", "language": "go", "file_size": 12151, "cut_index": 921, "middle_length": 229}}
{"prefix": "\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tbanner = \"Echo (v%s). High performance, minimalist Go web framework https://echo.labstack.com\"\n)\n\n// StartConfig is for creating configured http.Server instance to start serve http(s) requests with given Echo instance\ntype StartConfig struct {\n\t// Address specifies the address where listener will start listening on to serve HTTP(s) requests\n\tAddress string\n\n\t// HideBanner instructs Start* method not to print banner when starting the Server.\n\tHideBanner ", "suffix": "\n\n\t// TLSConfig is used to configure TLS. If Listener is set, TLSConfig is not used to create the listener.\n\tTLSConfig *tls.Config\n\n\t// Listener is used to start server with the custom listener.\n\tListener net.Listener\n\t// ListenerNetwork is used configure ", "middle": "bool\n\t// HidePort instructs Start* method not to print port when starting the Server.\n\tHidePort bool\n\n\t// CertFilesystem is filesystem is used to read `certFile` and `keyFile` when StartTLS method is called.\n\tCertFilesystem fs.FS", "meta": {"filepath": "server.go", "language": "go", "file_size": 6290, "cut_index": 716, "middle_length": 229}}
{"prefix": "/ NewConcurrentRouter creates concurrency safe Router which routes can be added/removed safely\n// even after http.Server has been started.\nfunc NewConcurrentRouter(r Router) Router {\n\treturn &concurrentRouter{\n\t\tmu: sync.RWMutex{},\n\t\trouter: r,\n\t}\n}\n\ntype concurrentRouter struct {\n\tmu sync.RWMutex\n\trouter Router\n}\n\nfunc (r *concurrentRouter) Route(c *Context) HandlerFunc {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\n\treturn r.router.Route(c)\n}\n\nfunc (r *concurrentRouter) Routes() Routes {\n\tr.mu.RLock()\n\tde", "suffix": ")\n}\n\nfunc (r *concurrentRouter) Add(routable Route) (RouteInfo, error) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\treturn r.router.Add(routable)\n}\n\nfunc (r *concurrentRouter) Remove(method string, path string) error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\treturn r", "middle": "fer r.mu.RUnlock()\n\n\treturn r.router.Routes().Clone(", "meta": {"filepath": "router_concurrent.go", "language": "go", "file_size": 886, "cut_index": 547, "middle_length": 52}}
{"prefix": "package echo\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc TestVirtualHostHandler(t *testing.T) {\n\tokHandler := func(c *Context) error { return c.String(http.StatusOK, http.StatusText(http.StatusOK)) }\n\tteapotHandler := func(c *Context) error { return c.String(http.StatusTeapot, http.StatusText(http.StatusTeapot)) }\n\tacceptHandler := func(c *Context) error { return c.String(http.StatusAccepted, http.StatusText(http.StatusAccepted)) }\n\tteapotMiddleware :=", "suffix": "middle := New()\n\tmiddle.Use(teapotMiddleware)\n\tmiddle.GET(\"/\", okHandler)\n\tmiddle.GET(\"/foo\", okHandler)\n\n\tvirtualHosts := NewVirtualHostHandler(map[string]*Echo{\n\t\t\"ok.com\": ok,\n\t\t\"teapot.com\": teapot,\n\t\t\"middleware.com\": middle,\n\t})\n\tvirtualH", "middle": " MiddlewareFunc(func(next HandlerFunc) HandlerFunc { return teapotHandler })\n\n\tok := New()\n\tok.GET(\"/\", okHandler)\n\tok.GET(\"/foo\", okHandler)\n\n\tteapot := New()\n\tteapot.GET(\"/\", teapotHandler)\n\tteapot.GET(\"/foo\", teapotHandler)\n\n\t", "meta": {"filepath": "vhost_test.go", "language": "go", "file_size": 3125, "cut_index": 614, "middle_length": 229}}
{"prefix": "test\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/labstack/echo/v5\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestBasicAuth(t *testing.T) {\n\tvalidatorFunc := func(c *echo.Context, u, p string) (bool, error) {\n\t\t// Use constant-time comparison to prevent timing attacks\n\t\tuserMatch := subtle.ConstantTimeCompare([]byte(u), []byte(\"joe\")) == 1\n\t\tpassMatch := subtle.ConstantTimeCompare([]byte(p), []byte(\"secret\")) == 1\n\n\t\tif userMatch && passMatch {\n\t\t\treturn true, nil\n\t\t}\n\n\t\t// Special case for testing error handli", "suffix": "nAuth []string\n\t\texpectHeader string\n\t\texpectErr string\n\t}{\n\t\t{\n\t\t\tname: \"ok\",\n\t\t\tgivenConfig: defaultConfig,\n\t\t\twhenAuth: []string{basic + \" \" + base64.StdEncoding.EncodeToString([]byte(\"joe:secret\"))},\n\t\t},\n\t\t{\n\t\t\tname: \"ok, multi", "middle": "ng\n\t\tif u == \"error\" {\n\t\t\treturn false, errors.New(p)\n\t\t}\n\n\t\treturn false, nil\n\t}\n\tdefaultConfig := BasicAuthConfig{Validator: validatorFunc}\n\n\tvar testCases = []struct {\n\t\tname string\n\t\tgivenConfig BasicAuthConfig\n\t\twhe", "meta": {"filepath": "middleware/basic_auth_test.go", "language": "go", "file_size": 7043, "cut_index": 716, "middle_length": 229}}
{"prefix": "wReader(hw))\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\th := func(c *echo.Context) error {\n\t\tbody, err := io.ReadAll(c.Request().Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn c.String(http.StatusOK, string(body))\n\t}\n\n\trequestBody := \"\"\n\tresponseBody := \"\"\n\tmw, err := BodyDumpConfig{Handler: func(c *echo.Context, reqBody, resBody []byte, err error) {\n\t\trequestBody = string(reqBody)\n\t\tresponseBody = string(resBody)\n\t}}.ToMiddleware()\n\tassert.NoError(t, err)\n\n\tif assert.NoError(t, mw(h)(", "suffix": "isCalled := false\n\tmw, err := BodyDumpConfig{\n\t\tSkipper: func(c *echo.Context) bool {\n\t\t\treturn true\n\t\t},\n\t\tHandler: func(c *echo.Context, reqBody, resBody []byte, err error) {\n\t\t\tisCalled = true\n\t\t},\n\t}.ToMiddleware()\n\tassert.NoError(t, err)\n\n\treq := http", "middle": "c)) {\n\t\tassert.Equal(t, requestBody, hw)\n\t\tassert.Equal(t, responseBody, hw)\n\t\tassert.Equal(t, http.StatusOK, rec.Code)\n\t\tassert.Equal(t, hw, rec.Body.String())\n\t}\n\n}\n\nfunc TestBodyDump_skipper(t *testing.T) {\n\te := echo.New()\n\n\t", "meta": {"filepath": "middleware/body_dump_test.go", "language": "go", "file_size": 16736, "cut_index": 921, "middle_length": 229}}
{"prefix": "htText: © 2015 LabStack LLC and Echo contributors\n\npackage middleware\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"sync\"\n\n\t\"github.com/labstack/echo/v5\"\n)\n\n// BodyLimitConfig defines the config for BodyLimitWithConfig middleware.\ntype BodyLimitConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// LimitBytes is maximum allowed size in bytes for a request body\n\tLimitBytes int64\n}\n\ntype limitedReader struct {\n\tBodyLimitConfig\n\treader io.ReadCloser\n\tread int64\n}\n\n// BodyLimit returns a Bod", "suffix": " both `Content-Length` request\n// header and actual content read, which makes it super secure.\nfunc BodyLimit(limitBytes int64) echo.MiddlewareFunc {\n\treturn BodyLimitWithConfig(BodyLimitConfig{LimitBytes: limitBytes})\n}\n\n// BodyLimitWithConfig returns a B", "middle": "yLimit middleware.\n//\n// BodyLimit middleware sets the maximum allowed size for a request body, if the size exceeds the configured limit, it\n// sends \"413 - Request Entity Too Large\" response. The BodyLimit is determined based on", "meta": {"filepath": "middleware/body_limit.go", "language": "go", "file_size": 2752, "cut_index": 563, "middle_length": 229}}
{"prefix": "trings\"\n\t\"sync\"\n\n\t\"github.com/labstack/echo/v5\"\n)\n\nconst (\n\tgzipScheme = \"gzip\"\n)\n\n// GzipConfig defines the config for Gzip middleware.\ntype GzipConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// Gzip compression level.\n\t// Optional. Default value -1.\n\tLevel int\n\n\t// Length threshold before gzip compression is applied.\n\t// Optional. Default value 0.\n\t//\n\t// Most of the time you will not need to change the default. Compressing\n\t// a short response might increase the tra", "suffix": "\n\t//\n\t// See also:\n\t// https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits\n\tMinLength int\n}\n\ntype gzipResponseWriter struct {\n\tio.Writer\n\thttp.ResponseWriter\n\twroteHeader bool\n\twr", "middle": "nsmitted data because of the\n\t// gzip format overhead. Compressing the response will also consume CPU\n\t// and time on the server and the client (for decompressing). Depending on\n\t// your use case such a threshold might be useful.", "meta": {"filepath": "middleware/compress.go", "language": "go", "file_size": 6272, "cut_index": 716, "middle_length": 229}}
{"prefix": "m/labstack/echo/v5\"\n)\n\n// BodyDumpConfig defines the config for BodyDump middleware.\ntype BodyDumpConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// Handler receives request, response payloads and handler error if there are any.\n\t// Required.\n\tHandler BodyDumpHandler\n\n\t// MaxRequestBytes limits how much of the request body to dump.\n\t// If the request body exceeds this limit, only the first MaxRequestBytes\n\t// are dumped. The handler callback receives truncated data.\n\t//", "suffix": "limit, only the first MaxResponseBytes\n\t// are dumped. The handler callback receives truncated data.\n\t// Default: 5 * MB (5,242,880 bytes)\n\t// Set to -1 to disable limits (not recommended in production).\n\tMaxResponseBytes int64\n}\n\n// BodyDumpHandler receiv", "middle": " Default: 5 * MB (5,242,880 bytes)\n\t// Set to -1 to disable limits (not recommended in production).\n\tMaxRequestBytes int64\n\n\t// MaxResponseBytes limits how much of the response body to dump.\n\t// If the response body exceeds this ", "meta": {"filepath": "middleware/body_dump.go", "language": "go", "file_size": 5642, "cut_index": 716, "middle_length": 229}}
{"prefix": "package middleware\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/labstack/echo/v5\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestBodyLimitConfig_ToMiddleware(t *testing.T) {\n\te := echo.New()\n\thw := []byte(\"Hello, World!\")\n\treq := httptest.NewRequest(http.MethodPost, \"/\", bytes.NewReader(hw))\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\th := func(c *echo.Context) error {\n\t\tbody, err := io.ReadAll(c.Request().Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t", "suffix": "sert.Equal(t, http.StatusOK, rec.Code)\n\t\tassert.Equal(t, hw, rec.Body.Bytes())\n\t}\n\n\t// Based on content read (overlimit)\n\tmw, err = BodyLimitConfig{LimitBytes: 2}.ToMiddleware()\n\tassert.NoError(t, err)\n\the := mw(h)(c).(echo.HTTPStatusCoder)\n\tassert.Equal(t", "middle": "return c.String(http.StatusOK, string(body))\n\t}\n\n\t// Based on content length (within limit)\n\tmw, err := BodyLimitConfig{LimitBytes: 2 * MB}.ToMiddleware()\n\tassert.NoError(t, err)\n\n\terr = mw(h)(c)\n\tif assert.NoError(t, err) {\n\t\tas", "meta": {"filepath": "middleware/body_limit_test.go", "language": "go", "file_size": 4379, "cut_index": 614, "middle_length": 229}}
{"prefix": "package middleware\n\nimport (\n\t\"bytes\"\n\t\"cmp\"\n\t\"encoding/base64\"\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/labstack/echo/v5\"\n)\n\n// BasicAuthConfig defines the config for BasicAuthWithConfig middleware.\n//\n// SECURITY: The Validator function is responsible for securely comparing credentials.\n// See BasicAuthValidator documentation for guidance on preventing timing attacks.\ntype BasicAuthConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// Validator is a function to vali", "suffix": "\t// Realm is a string to define realm attribute of BasicAuthWithConfig.\n\t// Default value \"Restricted\".\n\tRealm string\n\n\t// AllowedCheckLimit set how many headers are allowed to be checked. This is useful\n\t// environments like corporate test environments wi", "middle": "date BasicAuthWithConfig credentials. Note: if request contains multiple basic auth headers\n\t// this function would be called once for each header until first valid result is returned\n\t// Required.\n\tValidator BasicAuthValidator\n\n", "meta": {"filepath": "middleware/basic_auth.go", "language": "go", "file_size": 4936, "cut_index": 614, "middle_length": 229}}
{"prefix": "r: MIT\n// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors\n\npackage middleware\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/labstack/echo/v5\"\n)\n\n// ContextTimeoutConfig defines the config for ContextTimeout middleware.\ntype ContextTimeoutConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// ErrorHandler is a function when error arises in middeware execution.\n\tErrorHandler func(c *echo.Context, err error) error\n\n\t// Timeout configures a timeout for ", "suffix": "imeout time.Duration) echo.MiddlewareFunc {\n\treturn ContextTimeoutWithConfig(ContextTimeoutConfig{Timeout: timeout})\n}\n\n// ContextTimeoutWithConfig returns a Timeout middleware with config.\nfunc ContextTimeoutWithConfig(config ContextTimeoutConfig) echo.Mi", "middle": "the middleware\n\tTimeout time.Duration\n}\n\n// ContextTimeout returns a middleware which returns error (503 Service Unavailable error) to client\n// when underlying method returns context.DeadlineExceeded error.\nfunc ContextTimeout(t", "meta": {"filepath": "middleware/context_timeout.go", "language": "go", "file_size": 2000, "cut_index": 537, "middle_length": 229}}
{"prefix": " Access-Control-Allow-Origin\n\t// response header. This header defines a list of origins that may access the\n\t// resource.\n\t//\n\t// Origin consist of following parts: `scheme + \"://\" + host + optional \":\" + port`\n\t// Wildcard can be used, but has to be set explicitly []string{\"*\"}\n\t// Example: `https://example.com`, `http://example.com:8080`, `*`\n\t//\n\t// Security: use extreme caution when handling the origin, and carefully\n\t// validate any logic. Remember that attackers may register hostile domain names.\n\t//", "suffix": "// UnsafeAllowOriginFunc is an optional custom function to validate the origin. It takes the\n\t// origin as an argument and returns\n\t// - string, allowed origin\n\t// - bool, true if allowed or false otherwise.\n\t// - error, if an error is returned, it is retu", "middle": " See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html\n\t// See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin\n\t//\n\t// Mandatory.\n\tAllowOrigins []string\n\n\t", "meta": {"filepath": "middleware/cors.go", "language": "go", "file_size": 12043, "cut_index": 921, "middle_length": 229}}
{"prefix": "n value that can be used to render CSRF token for form by handlers.\n//\n// We know that the client is using a browser that supports Sec-Fetch-Site header, so when the form is submitted in\n// the future with this dummy token value it is OK. Although the request is safe, the template rendered by the\n// handler may need this value to render CSRF token for form.\nconst CSRFUsingSecFetchSite = \"_echo_csrf_using_sec_fetch_site_\"\n\n// CSRFConfig defines the config for CSRF middleware.\ntype CSRFConfig struct {\n\t// Ski", "suffix": "gin header \"scheme://host[:port]\".\n\t//\n\t// See [Origin]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin\n\t// See [Sec-Fetch-Site]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#fetch-", "middle": "pper defines a function to skip middleware.\n\tSkipper Skipper\n\t// TrustedOrigins permits any request with `Sec-Fetch-Site` header whose `Origin` header\n\t// exactly matches a configured origin.\n\t// Values should be formatted as Ori", "meta": {"filepath": "middleware/csrf.go", "language": "go", "file_size": 10485, "cut_index": 921, "middle_length": 229}}
{"prefix": "package middleware\n\nimport (\n\t\"compress/gzip\"\n\t\"io\"\n\t\"net/http\"\n\t\"sync\"\n\n\t\"github.com/labstack/echo/v5\"\n)\n\n// DecompressConfig defines the config for Decompress middleware.\ntype DecompressConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// GzipDecompressPool defines an interface to provide the sync.Pool used to create/store Gzip readers\n\tGzipDecompressPool Decompressor\n\n\t// MaxDecompressedSize limits the maximum size of decompressed request body in bytes.\n\t// If the deco", "suffix": "ble limits (not recommended in production).\n\tMaxDecompressedSize int64\n}\n\n// GZIPEncoding content-encoding header if set to \"gzip\", decompress body contents.\nconst GZIPEncoding string = \"gzip\"\n\n// Decompressor is used to get the sync.Pool used by the middl", "middle": "mpressed body exceeds this limit, the middleware returns HTTP 413 error.\n\t// This prevents zip bomb attacks where small compressed payloads decompress to huge sizes.\n\t// Default: 100 * MB (104,857,600 bytes)\n\t// Set to -1 to disa", "meta": {"filepath": "middleware/decompress.go", "language": "go", "file_size": 4679, "cut_index": 614, "middle_length": 229}}
{"prefix": "st (\n\t// extractorLimit is arbitrary number to limit values extractor can return. this limits possible resource exhaustion\n\t// attack vector\n\textractorLimit = 20\n)\n\n// ExtractorSource is type to indicate source for extracted value\ntype ExtractorSource string\n\nconst (\n\t// ExtractorSourceHeader means value was extracted from request header\n\tExtractorSourceHeader ExtractorSource = \"header\"\n\t// ExtractorSourceQuery means value was extracted from request query parameters\n\tExtractorSourceQuery ExtractorSource = \"", "suffix": "eCookie ExtractorSource = \"cookie\"\n\t// ExtractorSourceForm means value was extracted from request form values\n\tExtractorSourceForm ExtractorSource = \"form\"\n)\n\n// ValueExtractorError is error type when middleware extractor is unable to extract value from lo", "middle": "query\"\n\t// ExtractorSourcePathParam means value was extracted from route path parameters\n\tExtractorSourcePathParam ExtractorSource = \"param\"\n\t// ExtractorSourceCookie means value was extracted from request cookies\n\tExtractorSourc", "meta": {"filepath": "middleware/extractor.go", "language": "go", "file_size": 8474, "cut_index": 716, "middle_length": 229}}
{"prefix": "p/httptest\"\n\t\"net/url\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestContextTimeoutSkipper(t *testing.T) {\n\tt.Parallel()\n\tm := ContextTimeoutWithConfig(ContextTimeoutConfig{\n\t\tSkipper: func(context *echo.Context) bool {\n\t\t\treturn true\n\t\t},\n\t\tTimeout: 10 * time.Millisecond,\n\t})\n\n\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\trec := httptest.NewRecorder()\n\n\te := echo.New()\n\tc := e.NewContext(req, rec)\n\n\terr := m(func(c *echo.Context) error {\n\t\tif err := sleepWithCont", "suffix": "ssert.EqualError(t, err, \"response from handler\")\n}\n\nfunc TestContextTimeoutWithTimeout0(t *testing.T) {\n\tt.Parallel()\n\tassert.Panics(t, func() {\n\t\tContextTimeout(time.Duration(0))\n\t})\n}\n\nfunc TestContextTimeoutErrorOutInHandler(t *testing.T) {\n\tt.Parallel", "middle": "ext(c.Request().Context(), time.Duration(20*time.Millisecond)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn errors.New(\"response from handler\")\n\t})(c)\n\n\t// if not skipped we would have not returned error due context timeout logic\n\ta", "meta": {"filepath": "middleware/context_timeout_test.go", "language": "go", "file_size": 6301, "cut_index": 716, "middle_length": 229}}
{"prefix": "nLookup: \"header:X-CSRF-Token,form:csrf\",\n\t\t\tgivenCSRFCookie: \"token\",\n\t\t\tgivenMethod: http.MethodPost,\n\t\t\tgivenHeaderTokens: map[string][]string{\n\t\t\t\techo.HeaderXCSRFToken: {\"invalid_token\"},\n\t\t\t},\n\t\t\tgivenFormTokens: map[string][]string{\n\t\t\t\t\"csrf\": {\"token\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"ok, token from POST form\",\n\t\t\twhenTokenLookup: \"form:csrf\",\n\t\t\tgivenCSRFCookie: \"token\",\n\t\t\tgivenMethod: http.MethodPost,\n\t\t\tgivenFormTokens: map[string][]string{\n\t\t\t\t\"csrf\": {\"token\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tn", "suffix": "\"token\"},\n\t\t\t},\n\t\t\texpectError: \"code=403, message=invalid csrf token\",\n\t\t},\n\t\t{\n\t\t\tname: \"nok, invalid token from POST form\",\n\t\t\twhenTokenLookup: \"form:csrf\",\n\t\t\tgivenCSRFCookie: \"token\",\n\t\t\tgivenMethod: http.MethodPost,\n\t\t\tgivenFormTokens:", "middle": "ame: \"ok, token from POST form, second token passes\",\n\t\t\twhenTokenLookup: \"form:csrf\",\n\t\t\tgivenCSRFCookie: \"token\",\n\t\t\tgivenMethod: http.MethodPost,\n\t\t\tgivenFormTokens: map[string][]string{\n\t\t\t\t\"csrf\": {\"invalid\", ", "meta": {"filepath": "middleware/csrf_test.go", "language": "go", "file_size": 25419, "cut_index": 1331, "middle_length": 229}}
{"prefix": " {\n\t\tc.Response().Write([]byte(\"test\")) // For Content-Type sniffing\n\t\treturn nil\n\t})\n\n\t// Decompress request body\n\tbody := `{\"name\": \"echo\"}`\n\tgz, _ := gzipString(body)\n\treq := httptest.NewRequest(http.MethodPost, \"/\", strings.NewReader(string(gz)))\n\treq.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\n\terr := h(c)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, GZIPEncoding, req.Header.Get(echo.HeaderContentEncoding))\n\tb, err := io.ReadAll(req.Bod", "suffix": "NewRecorder()\n\tc := e.NewContext(req, rec)\n\n\t// Skip if no Content-Encoding header\n\th := Decompress()(func(c *echo.Context) error {\n\t\tc.Response().Write([]byte(\"test\")) // For Content-Type sniffing\n\t\treturn nil\n\t})\n\n\terr := h(c)\n\tassert.NoError(t, err)\n\tas", "middle": "y)\n\tassert.NoError(t, err)\n\tassert.Equal(t, body, string(b))\n}\n\nfunc TestDecompress_skippedIfNoHeader(t *testing.T) {\n\te := echo.New()\n\treq := httptest.NewRequest(http.MethodPost, \"/\", strings.NewReader(\"test\"))\n\trec := httptest.", "meta": {"filepath": "middleware/decompress_test.go", "language": "go", "file_size": 13852, "cut_index": 921, "middle_length": 229}}
{"prefix": "ses = []struct {\n\t\tname string\n\t\tgivenConfig *CORSConfig\n\t\twhenMethod string\n\t\twhenHeaders map[string]string\n\t\texpectHeaders map[string]string\n\t\tnotExpectHeaders map[string]string\n\t\texpectErr string\n\t}{\n\t\t{\n\t\t\tname: \"ok, wildcard origin\",\n\t\t\tgivenConfig: &CORSConfig{\n\t\t\t\tAllowOrigins: []string{\"*\"},\n\t\t\t},\n\t\t\twhenHeaders: map[string]string{echo.HeaderOrigin: \"localhost\"},\n\t\t\texpectHeaders: map[string]string{echo.HeaderAccessControlAllowOrigin: \"*\"},\n\t\t},\n\t\t{\n\t\t\tname: \"", "suffix": "\"ok, specific AllowOrigins and AllowCredentials\",\n\t\t\tgivenConfig: &CORSConfig{\n\t\t\t\tAllowOrigins: []string{\"http://localhost\", \"http://localhost:8080\"},\n\t\t\t\tAllowCredentials: true,\n\t\t\t\tMaxAge: 3600,\n\t\t\t},\n\t\t\twhenHeaders: map[string]string{echo", "middle": "ok, wildcard AllowedOrigin with no Origin header in request\",\n\t\t\tgivenConfig: &CORSConfig{\n\t\t\t\tAllowOrigins: []string{\"*\"},\n\t\t\t},\n\t\t\tnotExpectHeaders: map[string]string{echo.HeaderAccessControlAllowOrigin: \"\"},\n\t\t},\n\t\t{\n\t\t\tname: ", "meta": {"filepath": "middleware/cors_test.go", "language": "go", "file_size": 20362, "cut_index": 1331, "middle_length": 229}}
{"prefix": " KeyAuthConfig defines the config for KeyAuth middleware.\n//\n// SECURITY: The Validator function is responsible for securely comparing API keys.\n// See KeyAuthValidator documentation for guidance on preventing timing attacks.\ntype KeyAuthConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// KeyLookup is a string in the form of \":\" or \":,:\" that is used\n\t// to extract key from the request.\n\t// Optional. Default value \"header:Authori", "suffix": "uthorization: ` where part that we\n\t//\t\t\twant to cut is ` ` note the space at the end.\n\t//\t\t\tIn case of basic authentication `Authorization: Basic ` prefix we want to remove is `Basic `.\n\t//", "middle": "zation\".\n\t// Possible values:\n\t// - \"header:\" or \"header::\"\n\t// \t\t\t`` is argument value to cut/trim prefix of the extracted value. This is useful if header\n\t//\t\t\tvalue has static prefix like `A", "meta": {"filepath": "middleware/key_auth.go", "language": "go", "file_size": 7504, "cut_index": 716, "middle_length": 229}}
{"prefix": "htText: © 2015 LabStack LLC and Echo contributors\n\npackage middleware\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/labstack/echo/v5\"\n)\n\n// MethodOverrideConfig defines the config for MethodOverride middleware.\ntype MethodOverrideConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// Getter is a function that gets overridden method from the request.\n\t// Optional. Default values MethodFromHeader(echo.HeaderXHTTPMethodOverride).\n\tGetter MethodOverrideGetter\n}\n\n// MethodOverrideGetter i", "suffix": "ethodOverrideConfig{\n\tSkipper: DefaultSkipper,\n\tGetter: MethodFromHeader(echo.HeaderXHTTPMethodOverride),\n}\n\n// MethodOverride returns a MethodOverride middleware.\n// MethodOverride middleware checks for the overridden method from the request and\n// uses", "middle": "s a function that gets overridden method from the request\ntype MethodOverrideGetter func(c *echo.Context) string\n\n// DefaultMethodOverrideConfig is the default MethodOverride middleware config.\nvar DefaultMethodOverrideConfig = M", "meta": {"filepath": "middleware/method_override.go", "language": "go", "file_size": 2891, "cut_index": 563, "middle_length": 229}}
{"prefix": "htText: © 2015 LabStack LLC and Echo contributors\n\npackage middleware\n\nimport (\n\t\"net/http\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/labstack/echo/v5\"\n)\n\n// Skipper defines a function to skip middleware. Returning true skips processing the middleware.\ntype Skipper func(c *echo.Context) bool\n\n// BeforeFunc defines a function which is executed just before the middleware.\ntype BeforeFunc func(c *echo.Context)\n\nfunc captureTokens(pattern *regexp.Regexp, input string) *strings.Replacer {\n\tgroups := pattern.", "suffix": "] = v\n\t}\n\treturn strings.NewReplacer(replace...)\n}\n\nfunc rewriteRulesRegex(rewrite map[string]string) map[*regexp.Regexp]string {\n\t// Initialize\n\trulesRegex := map[*regexp.Regexp]string{}\n\tfor k, v := range rewrite {\n\t\tk = regexp.QuoteMeta(k)\n\t\tk = strings", "middle": "FindAllStringSubmatch(input, -1)\n\tif groups == nil {\n\t\treturn nil\n\t}\n\tvalues := groups[0][1:]\n\treplace := make([]string, 2*len(values))\n\tfor i, v := range values {\n\t\tj := 2 * i\n\t\treplace[j] = \"$\" + strconv.Itoa(i+1)\n\t\treplace[j+1", "meta": {"filepath": "middleware/middleware.go", "language": "go", "file_size": 2399, "cut_index": 563, "middle_length": 229}}
{"prefix": "e ProxyConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// Balancer defines a load balancing technique.\n\t// Required.\n\tBalancer ProxyBalancer\n\n\t// RetryCount defines the number of times a failed proxied request should be retried\n\t// using the next available ProxyTarget. Defaults to 0, meaning requests are never retried.\n\tRetryCount int\n\n\t// RetryFilter defines a function used to determine if a failed request to a\n\t// ProxyTarget should be retried. The RetryFilter will on", "suffix": "t is unavailable, the error will be an instance of\n\t// echo.HTTPError with a code of http.StatusBadGateway. In all other cases, the error\n\t// will indicate an internal error in the Proxy middleware. When a RetryFilter is not\n\t// specified, all requests tha", "middle": "ly be called when the number\n\t// of previous retries is less than RetryCount. If the function returns true, the\n\t// request will be retried. The provided error indicates the reason for the request\n\t// failure. When the ProxyTarge", "meta": {"filepath": "middleware/proxy.go", "language": "go", "file_size": 14718, "cut_index": 921, "middle_length": 229}}
{"prefix": "/v5\"\n\t\"golang.org/x/time/rate\"\n)\n\n// RateLimiterStore is the interface to be implemented by custom stores.\ntype RateLimiterStore interface {\n\tAllow(identifier string) (bool, error)\n}\n\n// RateLimiterConfig defines the configuration for the rate limiter\ntype RateLimiterConfig struct {\n\tSkipper Skipper\n\tBeforeFunc BeforeFunc\n\t// IdentifierExtractor uses *echo.Context to extract the identifier for a visitor\n\tIdentifierExtractor Extractor\n\t// Store defines a store for the rate limiter\n\tStore RateLimiterStore\n", "suffix": "andler func(c *echo.Context, identifier string, err error) error\n}\n\n// Extractor is used to extract data from *echo.Context\ntype Extractor func(c *echo.Context) (string, error)\n\n// ErrRateLimitExceeded denotes an error raised when rate limit is exceeded\nva", "middle": "\t// ErrorHandler provides a handler to be called when IdentifierExtractor returns an error\n\tErrorHandler func(c *echo.Context, err error) error\n\t// DenyHandler provides a handler to be called when RateLimiter denies access\n\tDenyH", "meta": {"filepath": "middleware/rate_limiter.go", "language": "go", "file_size": 8709, "cut_index": 716, "middle_length": 229}}
{"prefix": " to prevent timing attacks\n\tif subtle.ConstantTimeCompare([]byte(key), []byte(\"valid-key\")) == 1 {\n\t\treturn true, nil\n\t}\n\n\t// Special case for testing error handling\n\tif key == \"error-key\" { // Error path doesn't need constant-time\n\t\treturn false, errors.New(\"some user defined error\")\n\t}\n\n\treturn false, nil\n}\n\nfunc TestKeyAuth(t *testing.T) {\n\thandlerCalled := false\n\thandler := func(c *echo.Context) error {\n\t\thandlerCalled = true\n\t\treturn c.String(http.StatusOK, \"test\")\n\t}\n\tmiddlewareChain := KeyAuth(testKe", "suffix": "ewareChain(c)\n\n\tassert.NoError(t, err)\n\tassert.True(t, handlerCalled)\n}\n\nfunc TestKeyAuthWithConfig(t *testing.T) {\n\tvar testCases = []struct {\n\t\tname string\n\t\tgivenRequestFunc func() *http.Request\n\t\tgivenRequest func(req *http.Req", "middle": "yValidator)(handler)\n\n\te := echo.New()\n\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\treq.Header.Set(echo.HeaderAuthorization, \"Bearer valid-key\")\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\n\terr := middl", "meta": {"filepath": "middleware/key_auth_test.go", "language": "go", "file_size": 10694, "cut_index": 921, "middle_length": 229}}
{"prefix": "htText: © 2015 LabStack LLC and Echo contributors\n\npackage middleware\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/labstack/echo/v5\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestMethodOverride(t *testing.T) {\n\te := echo.New()\n\tm := MethodOverride()\n\th := func(c *echo.Context) error {\n\t\treturn c.String(http.StatusOK, \"test\")\n\t}\n\n\t// Override with http header\n\treq := httptest.NewRequest(http.MethodPost, \"/\", nil)\n\trec := httptest.NewRecorder()\n\treq.Header.Set(echo.HeaderXH", "suffix": "h := func(c *echo.Context) error {\n\t\treturn c.String(http.StatusOK, \"test\")\n\t}\n\n\t// Override with form parameter\n\tm, err := MethodOverrideConfig{Getter: MethodFromForm(\"_method\")}.ToMiddleware()\n\tassert.NoError(t, err)\n\treq := httptest.NewRequest(http.Meth", "middle": "TTPMethodOverride, http.MethodDelete)\n\tc := e.NewContext(req, rec)\n\n\terr := m(h)(c)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, http.MethodDelete, req.Method)\n\n}\n\nfunc TestMethodOverride_formParam(t *testing.T) {\n\te := echo.New()\n\t", "meta": {"filepath": "middleware/method_override_test.go", "language": "go", "file_size": 2317, "cut_index": 563, "middle_length": 229}}
{"prefix": "e(t2.URL)\n\n\ttargets := []*ProxyTarget{\n\t\t{\n\t\t\tName: \"target 1\",\n\t\t\tURL: url1,\n\t\t},\n\t\t{\n\t\t\tName: \"target 2\",\n\t\t\tURL: url2,\n\t\t},\n\t}\n\trb := NewRandomBalancer(nil)\n\t// must add targets:\n\tfor _, target := range targets {\n\t\tassert.True(t, rb.AddTarget(target))\n\t}\n\n\t// must ignore duplicates:\n\tfor _, target := range targets {\n\t\tassert.False(t, rb.AddTarget(target))\n\t}\n\n\t// Random\n\te := echo.New()\n\te.Use(ProxyWithConfig(ProxyConfig{Balancer: rb}))\n\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\trec := http", "suffix": " targets {\n\t\tassert.True(t, rb.RemoveTarget(target.Name))\n\t}\n\n\tassert.False(t, rb.RemoveTarget(\"unknown target\"))\n\n\t// Round-robin\n\trrb := NewRoundRobinBalancer(targets)\n\te = echo.New()\n\te.Use(ProxyWithConfig(ProxyConfig{Balancer: rrb}))\n\n\trec = httptest.N", "middle": "test.NewRecorder()\n\te.ServeHTTP(rec, req)\n\tbody := rec.Body.String()\n\texpected := map[string]bool{\n\t\t\"target 1\": true,\n\t\t\"target 2\": true,\n\t}\n\tassert.Condition(t, func() bool {\n\t\treturn expected[body]\n\t})\n\n\tfor _, target := range", "meta": {"filepath": "middleware/proxy_test.go", "language": "go", "file_size": 30524, "cut_index": 1331, "middle_length": 229}}
{"prefix": "package middleware\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"regexp\"\n\t\"testing\"\n)\n\nfunc TestRewriteURL(t *testing.T) {\n\tvar testCases = []struct {\n\t\twhenURL string\n\t\texpectPath string\n\t\texpectRawPath string\n\t\texpectQuery string\n\t\texpectErr string\n\t}{\n\t\t{\n\t\t\twhenURL: \"http://localhost:8080/old\",\n\t\t\texpectPath: \"/new\",\n\t\t\texpectRawPath: \"\",\n\t\t},\n\t\t{ // encoded `ol%64` (decoded `old`) should not be rewritten to `/new`\n\t\t", "suffix": "+\",\n\t\t\texpectRawPath: \"\",\n\t\t\texpectQuery: \"test=1\",\n\t\t},\n\t\t{\n\t\t\twhenURL: \"http://localhost:8080/users/%20a/orders/%20aa\",\n\t\t\texpectPath: \"/user/ a/order/ aa\",\n\t\t\texpectRawPath: \"\",\n\t\t},\n\t\t{\n\t\t\twhenURL: \"http://localhost:8080/%47%6f%2f?test", "middle": "\twhenURL: \"/ol%64\", // `%64` is decoded `d`\n\t\t\texpectPath: \"/old\",\n\t\t\texpectRawPath: \"/ol%64\",\n\t\t},\n\t\t{\n\t\t\twhenURL: \"http://localhost:8080/users/+_+/orders/___++++?test=1\",\n\t\t\texpectPath: \"/user/+_+/order/___+++", "meta": {"filepath": "middleware/middleware_test.go", "language": "go", "file_size": 3740, "cut_index": 614, "middle_length": 229}}
{"prefix": "package middleware\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/labstack/echo/v5\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestRecover(t *testing.T) {\n\te := echo.New()\n\tbuf := new(bytes.Buffer)\n\te.Logger = slog.New(&discardHandler{})\n\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\th := Recover()(func(c *echo.Context) error {\n\t\tpanic(\"test\")\n\t})\n\terr := h(c)\n\tassert.Contains(t, err.Er", "suffix": ".Equal(t, http.StatusOK, rec.Code) // status is still untouched. err is returned from middleware chain\n\tassert.Contains(t, buf.String(), \"\") // nothing is logged\n}\n\nfunc TestRecover_skipper(t *testing.T) {\n\te := echo.New()\n\n\treq := httptest.NewRequest(", "middle": "ror(), \"[PANIC RECOVER] test goroutine\")\n\n\tvar pse *PanicStackError\n\tif errors.As(err, &pse) {\n\t\tassert.Contains(t, string(pse.Stack), \"middleware/recover.go\")\n\t} else {\n\t\tassert.Fail(t, \"not of type PanicStackError\")\n\t}\n\n\tassert", "meta": {"filepath": "middleware/recover_test.go", "language": "go", "file_size": 3606, "cut_index": 614, "middle_length": 229}}
{"prefix": "5\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype middlewareGenerator func() echo.MiddlewareFunc\n\nfunc TestRedirectHTTPSRedirect(t *testing.T) {\n\tvar testCases = []struct {\n\t\twhenHost string\n\t\twhenHeader http.Header\n\t\texpectLocation string\n\t\texpectStatusCode int\n\t}{\n\t\t{\n\t\t\twhenHost: \"labstack.com\",\n\t\t\texpectLocation: \"https://labstack.com/\",\n\t\t\texpectStatusCode: http.StatusMovedPermanently,\n\t\t},\n\t\t{\n\t\t\twhenHost: \"labstack.com\",\n\t\t\twhenHeader: map[string][]string{echo.H", "suffix": "tc.whenHeader)\n\n\t\t\tassert.Equal(t, tc.expectStatusCode, res.Code)\n\t\t\tassert.Equal(t, tc.expectLocation, res.Header().Get(echo.HeaderLocation))\n\t\t})\n\t}\n}\n\nfunc TestRedirectHTTPSWWWRedirect(t *testing.T) {\n\tvar testCases = []struct {\n\t\twhenHost strin", "middle": "eaderXForwardedProto: {\"https\"}},\n\t\t\texpectLocation: \"\",\n\t\t\texpectStatusCode: http.StatusOK,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.whenHost, func(t *testing.T) {\n\t\t\tres := redirectTest(HTTPSRedirect, tc.whenHost, ", "meta": {"filepath": "middleware/redirect_test.go", "language": "go", "file_size": 7865, "cut_index": 716, "middle_length": 229}}
{"prefix": "package middleware\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/labstack/echo/v5\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestRequestID(t *testing.T) {\n\te := echo.New()\n\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\thandler := func(c *echo.Context) error {\n\t\treturn c.String(http.StatusOK, \"test\")\n\t}\n\n\trid := RequestID()\n\th := rid(handler)\n\terr := h(c)\n\tassert.NoError(t, err)\n\tassert.Len(t, rec.Header().Get(echo.", "suffix": "estIDWithConfig(RequestIDConfig{\n\t\tSkipper: func(c *echo.Context) bool {\n\t\t\treturn true\n\t\t},\n\t\tGenerator: func() string {\n\t\t\tgeneratorCalled = true\n\t\t\treturn \"customGenerator\"\n\t\t},\n\t}))\n\n\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\tres := httptes", "middle": "HeaderXRequestID), 32)\n}\n\nfunc TestMustRequestIDWithConfig_skipper(t *testing.T) {\n\te := echo.New()\n\te.GET(\"/\", func(c *echo.Context) error {\n\t\treturn c.String(http.StatusTeapot, \"test\")\n\t})\n\n\tgeneratorCalled := false\n\te.Use(Requ", "meta": {"filepath": "middleware/request_id_test.go", "language": "go", "file_size": 4571, "cut_index": 614, "middle_length": 229}}
{"prefix": "Header.Set(echo.HeaderContentLength, strconv.Itoa(int(reader.Size())))\n\treq.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)\n\treq.Header.Set(echo.HeaderXRealIP, \"8.8.8.8\")\n\treq.Header.Set(\"User-Agent\", \"curl/7.68.0\")\n\n\trec := httptest.NewRecorder()\n\te.ServeHTTP(rec, req)\n\n\tlogAttrs := map[string]any{}\n\tassert.NoError(t, json.Unmarshal(buf.Bytes(), &logAttrs))\n\tlogAttrs[\"latency\"] = 123\n\tlogAttrs[\"time\"] = \"x\"\n\n\texpect := map[string]any{\n\t\t\"level\": \"INFO\",\n\t\t\"msg\": \"REQUEST\",\n\t\t\"metho", "suffix": "\n\n\t\t\"time\": \"x\",\n\t\t\"latency\": 123,\n\t}\n\tassert.Equal(t, expect, logAttrs)\n}\n\nfunc TestRequestLoggerError(t *testing.T) {\n\told := slog.Default()\n\tt.Cleanup(func() {\n\t\tslog.SetDefault(old)\n\t})\n\n\te := echo.New()\n\tbuf := new(bytes.Buffer)\n\te.Logger = slog.Ne", "middle": "d\": \"POST\",\n\t\t\"uri\": \"/test\",\n\t\t\"status\": float64(418),\n\t\t\"bytes_in\": \"13\",\n\t\t\"host\": \"example.com\",\n\t\t\"bytes_out\": float64(2),\n\t\t\"user_agent\": \"curl/7.68.0\",\n\t\t\"remote_ip\": \"8.8.8.8\",\n\t\t\"request_id\": \"\",", "meta": {"filepath": "middleware/request_logger_test.go", "language": "go", "file_size": 17585, "cut_index": 1331, "middle_length": 229}}
{"prefix": " message=rate limit exceeded\"},\n\t\t{id: \"127.0.0.1\", expectErr: \"code=429, message=rate limit exceeded\"},\n\t\t{id: \"127.0.0.1\", expectErr: \"code=429, message=rate limit exceeded\"},\n\t\t{id: \"127.0.0.1\", expectErr: \"code=429, message=rate limit exceeded\"},\n\t}\n\n\tfor _, tc := range testCases {\n\t\treq := httptest.NewRequest(http.MethodGet, \"/\", nil)\n\t\treq.Header.Add(echo.HeaderXRealIP, tc.id)\n\n\t\trec := httptest.NewRecorder()\n\t\tc := e.NewContext(req, rec)\n\n\t\terr := mw(handler)(c)\n\t\tif tc.expectErr != \"\" {\n\t\t\tassert.Eq", "suffix": "toreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3})\n\n\tassert.Panics(t, func() {\n\t\tRateLimiterWithConfig(RateLimiterConfig{})\n\t})\n\n\tassert.NotPanics(t, func() {\n\t\tRateLimiterWithConfig(RateLimiterConfig{Store: inMemoryStore})\n\t})\n}\n\nfunc TestRat", "middle": "ualError(t, err, tc.expectErr)\n\t\t} else {\n\t\t\tassert.NoError(t, err)\n\t\t}\n\t\tassert.Equal(t, http.StatusOK, rec.Code)\n\t}\n}\n\nfunc TestMustRateLimiterWithConfig_panicBehaviour(t *testing.T) {\n\tvar inMemoryStore = NewRateLimiterMemoryS", "meta": {"filepath": "middleware/rate_limiter_test.go", "language": "go", "file_size": 17806, "cut_index": 1331, "middle_length": 229}}
{"prefix": "htText: © 2015 LabStack LLC and Echo contributors\n\npackage middleware\n\nimport (\n\t\"github.com/labstack/echo/v5\"\n)\n\n// RequestIDConfig defines the config for RequestID middleware.\ntype RequestIDConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// Generator defines a function to generate an ID.\n\t// Optional. Default value random.String(32).\n\tGenerator func() string\n\n\t// RequestIDHandler defines a function which is executed for a request id.\n\tRequestIDHandler func(c *echo.Con", "suffix": "etHeader (`X-Request-ID`) header value or when\n// the header value is empty, generates that value and sets request ID to response\n// as RequestIDConfig.TargetHeader (`X-Request-Id`) value.\nfunc RequestID() echo.MiddlewareFunc {\n\treturn RequestIDWithConfig(", "middle": "text, requestID string)\n\n\t// TargetHeader defines what header to look for to populate the id.\n\t// Optional. Default value is `X-Request-Id`\n\tTargetHeader string\n}\n\n// RequestID returns a middleware that reads RequestIDConfig.Targ", "meta": {"filepath": "middleware/request_id.go", "language": "go", "file_size": 2372, "cut_index": 563, "middle_length": 229}}
{"prefix": "htText: © 2015 LabStack LLC and Echo contributors\n\npackage middleware\n\nimport (\n\t\"errors\"\n\t\"maps\"\n\t\"regexp\"\n\n\t\"github.com/labstack/echo/v5\"\n)\n\n// RewriteConfig defines the config for Rewrite middleware.\ntype RewriteConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// Rules defines the URL path rewrite rules. The values captured in asterisk can be\n\t// retrieved by index e.g. $1, $2 and so on.\n\t// Example:\n\t// \"/old\": \"/new\",\n\t// \"/api/*\": \"/$1\",\n\t//", "suffix": "apture group in the values can be retrieved by index e.g. $1, $2 and so on.\n\t// Example:\n\t// \"^/old/[0.9]+/\": \"/new\",\n\t// \"^/api/.+?/(.*)\": \"/v2/$1\",\n\tRegexRules map[*regexp.Regexp]string\n}\n\n// Rewrite returns a Rewrite middleware.\n//\n// Rewrite mi", "middle": " \"/js/*\": \"/public/javascripts/$1\",\n\t// \"/users/*/orders/*\": \"/user/$1/order/$2\",\n\t// Required.\n\tRules map[string]string\n\n\t// RegexRules defines the URL path rewrite rules using regexp.Rexexp with captures\n\t// Every c", "meta": {"filepath": "middleware/rewrite.go", "language": "go", "file_size": 2328, "cut_index": 563, "middle_length": 229}}
{"prefix": "directConfig defines the config for Redirect middleware.\ntype RedirectConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper\n\n\t// Status code to be used when redirecting the request.\n\t// Optional. Default value http.StatusMovedPermanently.\n\tCode int\n\n\tredirect redirectLogic\n}\n\n// redirectLogic represents a function that given a scheme, host and uri\n// can both: 1) determine if redirect is needed (will set ok accordingly) and\n// 2) return the appropriate redirect url.\ntype redirectLogic ", "suffix": "g is the HTTPS WWW Redirect middleware config.\nvar RedirectHTTPSWWWConfig = RedirectConfig{redirect: redirectHTTPSWWW}\n\n// RedirectNonHTTPSWWWConfig is the non HTTPS WWW Redirect middleware config.\nvar RedirectNonHTTPSWWWConfig = RedirectConfig{redirect: r", "middle": "func(scheme, host, uri string) (ok bool, url string)\n\nconst www = \"www.\"\n\n// RedirectHTTPSConfig is the HTTPS Redirect middleware config.\nvar RedirectHTTPSConfig = RedirectConfig{redirect: redirectHTTPS}\n\n// RedirectHTTPSWWWConfi", "meta": {"filepath": "middleware/redirect.go", "language": "go", "file_size": 6132, "cut_index": 716, "middle_length": 229}}
{"prefix": "fig for Secure middleware.\ntype SecureConfig struct {\n\t// Skipper defines a function to skip middleware.\n\tSkipper Skipper\n\n\t// XSSProtection provides protection against cross-site scripting attack (XSS)\n\t// by setting the `X-XSS-Protection` header.\n\t// Optional. Default value \"1; mode=block\".\n\tXSSProtection string\n\n\t// ContentTypeNosniff provides protection against overriding Content-Type\n\t// header by setting the `X-Content-Type-Options` header.\n\t// Optional. Default value \"nosniff\".\n\tContentTypeNosniff st", "suffix": " content is not embedded into other sites.provides protection against\n\t// clickjacking.\n\t// Optional. Default value \"SAMEORIGIN\".\n\t// Possible values:\n\t// - \"SAMEORIGIN\" - The page can only be displayed in a frame on the same origin as the page itself.\n\t//", "middle": "ring\n\n\t// XFrameOptions can be used to indicate whether or not a browser should\n\t// be allowed to render a page in a ,