Replies: 60 comments 72 replies
-
|
reserved |
Beta Was this translation helpful? Give feedback.
-
|
reserved |
Beta Was this translation helpful? Give feedback.
-
|
Consider using echo.Config instead of echo.StartConfig |
Beta Was this translation helpful? Give feedback.
-
|
I would be very glad to see the middleware packages move to a separate Go module (or modules). (These proposed changes look great, btw) |
Beta Was this translation helpful? Give feedback.
-
|
Just came to check whether logging was more configurable now. That looks like the most important change IMO, thanks! |
Beta Was this translation helpful? Give feedback.
-
|
v5 seems perfect imho, good job |
Beta Was this translation helpful? Give feedback.
-
|
I just encountered #1744 (et-all) and didn't see it at first read through on the list of stuff being done here. Is that still intended to be addressed for V5? To explain my reasoning for having different params as that seemed to be a question, TLDR I have a many2one relationship. Specifically, |
Beta Was this translation helpful? Give feedback.
-
|
Remove Context c.Error(), use return err uniformly |
Beta Was this translation helpful? Give feedback.
-
|
Middleware is not recommended to be divided into separate packages, otherwise core upgrades, these sub-packages will not be maintained in time |
Beta Was this translation helpful? Give feedback.
-
|
maybe keep |
Beta Was this translation helpful? Give feedback.
-
|
v6 release date have plan? |
Beta Was this translation helpful? Give feedback.
-
|
The v5 proposal looks good, I don't mind the minor breaking changes to make the code more consistent. Regarding middleware, I do see the pros and cons of both approaches, my personal preference would be to keep the middleware in the main package. If/when I upgrde a major version of Echo then I would be uncertain if any external middleware also need to be upgraded. I would expect any middleware in the main package to be always compatible, but there's less of a guarantee that external middleware would remain compatible. Because of that I would probably spend more time researching the middleware repositories and running tests to check if they really are still compatible than if I 'only' had to do a search and replace to change the imports in my code. |
Beta Was this translation helpful? Give feedback.
-
JWTChanged Signatures |
Beta Was this translation helpful? Give feedback.
-
|
v4 DefaultBinder provides scoped binding methods (e.g. BindQueryParams, BindPathParams), is there any plans to update |
Beta Was this translation helpful? Give feedback.
-
|
For the CSRF middleware, it would be nice to support both Form and Query with a single config. Right now it's set up to only support one or the other, and it would nice to have the CSRF module would check both locations to see if the token is passed down. |
Beta Was this translation helpful? Give feedback.
-
|
Another change - start using Slog logger https://go.googlesource.com/proposal/+/master/design/56345-structured-logging.md Recently structured logging proposal was accepted for Go 1.21 golang/go#56345 Currently in |
Beta Was this translation helpful? Give feedback.
-
|
How much of a bad idea would be for v5 to add support for file binding (as in |
Beta Was this translation helpful? Give feedback.
-
|
Overall I like this proposal, but would suggest one change: instead of having a giant "middleware" repo, split each middleware into its own repo and allow users to select which specific middleware packages they want on their own. I only need 2-3 of them for most projects and would rather just |
Beta Was this translation helpful? Give feedback.
-
I hope add golang Generics support, type Echo[T ContextInterface] struct {
xxxxxx
}
func (*Echo[T ContextInterface]) GET(path string, h HandlerFunc[T], m ...MiddlewareFunc[T]) *Route {
return e.Add(http.MethodGet, path, h, m...)
}
func (e *Echo[T ContextInterface]) SetNewContextFunc(fn func(ec *Echo, pathParamAllocSize int) *T {
e.NewContextFunc = fn
}
type MyContext struct {
*echo.Context
UserData Data
XXXXX
}
// override QueryParam method
func (c *MyContext) QueryParam(name string) string {
return "prefix_" + c.Context.QueryParam(name)
}
// Echo instance
e := echo.New[MyContext]()
e.GET("/xxx", func(c *MyContext) error {
xxxxx
})
|
Beta Was this translation helpful? Give feedback.
-
|
Would the V5 version happen to support broitil compression? |
Beta Was this translation helpful? Give feedback.
-
I think this is a great move: it will free Echo developers to properly validate CORS configuration and report mistakes to callers. However, I think you should also get rid of |
Beta Was this translation helpful? Give feedback.
-
|
Its possible to make this configurable? https://github.com/labstack/echo/blob/master/context.go#L396 |
Beta Was this translation helpful? Give feedback.
-
|
Given that Go 1.22 has enhancements to net/http routing, will v5 make use of those enhancements. Same for how path parameters are handled. I recently found https://github.com/go-michi/michi |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
|
Supports fiber config when creating instances on fiber. Why not support echo in the same way? |
Beta Was this translation helpful? Give feedback.
-
|
Hi, do you have any estimate of when v5 might be released? |
Beta Was this translation helpful? Give feedback.
-
|
Is there a way to test the v5 ? |
Beta Was this translation helpful? Give feedback.
-
|
Is there any plan to support regex url match in router ? |
Beta Was this translation helpful? Give feedback.
-
|
Is this still a planned release? I would like to set static context data for a route at route registration, but that data shall be available in all middleware layers, but it will only be static per route. |
Beta Was this translation helpful? Give feedback.
-
|
It's been a bit quiet lately, and it's understandable that this being an open source project, there's not always time to focus on it. It would be amazing though, if anything related to this would be communicated in some shape or form, regardless of the status itself. Echo itself is still quite used afaik, but it's somewhat falling behind various improvements and changes that have happened throughout Go itself; sponsorships may also help but in the current form with Echo itself being under Labstack, I'm not sure how that works. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Dear community member, this is a proposal for Echo
v5, we seek your feedback of these proposed changes.NOTE: non-constructive feedback will be hidden/deleted. Negative criticism is welcome if it comes with arguments. Be
professional, respect others time reading/deciphering your point of view, this is not Twitter or any other informal chatroom.
Be professional
v5will be mostly maintenance release to clean up APIs (remove and/or move things around, fix API inconsistencies,fix internally maintenance pain-points, prepare more extendable router). Minimal amount of fancy new features or
performance gains/regressions - just annoying API changes for the unprepared :)
If you are not starting with new application you do not need to upgrade to v5.
We support both
v4andv5for some time (ala 1year) so current users would not be affected by our"busywork" with APIs. From maintainers perspective it seems doable as we do not have (huge/many) changes often.
And from library/framework user perspective it should be positive as you are not forced/rushed to upgrade without
actual benefits for you.
Schedule:
Update 06.01.2022:
v5on first week we will postpone it and tagv5.0.0-alphaat the end of January along with[email protected]. This is mainly because we did not prepare documentation and there have been couple of small changes. As this release does not bring much groundbreaking new things we are not in that hurry to release half-baked product.Branch for
v5proposal: https://github.com/labstack/echo/tree/v5_proposal_publicNOTE: there will be force pushes, squashing of commits etc in that branch before the release.
TLDR: noticeable/biggest breaking changes
(Context interface) removed method
Logger()- we encourage you to use your favourite Logging libraries (Log/Logrus/Zap/Zerolog etc).Your options are now:
c.Store("logger", myLogger)and in handleraccess it
logger := c.Get("logger").(*zerolog.Logger)(Context interface) renamed method
Param("id")toPathParam("id")Reasoning for that is: Method name
Paramis too ambiguous. Context interface already has methods like:which explicitly describe where that
*Paramor*Valuedata comes/originates from. NamePathParamis explicit as those methods.(echo instance) moved all fields,methods related running of the http(s) server to different struct
(echo instance) methods like
e.GET(...)now returns immutable Route object. Route name can not be changed with that object anymore.echo.Contextas an argument have it as a first argument. Most notable isdefault error handler signature change:
and prone to be misused by users for use-cases where there are better/proper solutions.
spin a coroutine in your handler and wait some time it to finish.
basic functionality to timeout proxied requests that Nginx/Apache/HaProxy etc already have.
Undecided, but worth the discussion:
echo-middlewarespackage (one package for all) and version it from5.0.0and leave out semantic versioning for that repo. Breaking changes are done in minor versions but not inpatch versions. so all Echo
v5stuff would be ala[email protected]. Some people would probably complainabout unnecessary dependencies (same as
echo-contrib) but Go modules does not actually compile module dependenciesthat are not used in your app and as of Go 1.17 dependencies that are not used are not even downloaded.
So if there are external dependencies in that repo it should be ok. Allowing breaking changes in minor version is
a little bit more convenient for user as he/she does not need to update packages on version
bump (with go mod major version bump means new package import paths but minor version does not generate new path).
As Go 1.18 probably brings us generics which maybe use for Echo, we may have soon
v6. So middleware relocation, if it seemsreasonable idea for the community, could be held back to that version.
General
Bumped minimal Go version to 1.16 as
fs.FSfilesystem was introduced in that version as we use it for fieldecho.Filesystemthat is used in methodse.File()ande.Static().Changed function fields that have
echo.Contextas an argument have it as a first argument. Most notable isdefault error handler signature change:
This is to normalize of callback function are defined. Previously
Contextwas sometimes first sometimes at some otherplace.
changed how type definitions are written from
to
This is because in that way it is easier to copy/paste Echo code when there are multiple definitions in one
()block.From personal perspective: have done this because it was quite inconvenient to paste code for
echoxdocumentation.Error handling
echo.HTTPError.SetInternal()method as it allowed to mutate global errors. UseHTTPError.WithInternal(err)instead.echo.NewHTTPErrorWithInternal()to help creating errors with internal error.echo.NotFoundHandlerto private. Replaced placed where it was called with actual error. 404 (echo.ErrNotFound) should now be handled in global error handler.echo.MethodNotAllowedHandlerto private. Replaced placed where it was called with actual error. 405 (echo.ErrMethodNotAllowed) should now be handled in global error handler.echo.EchostructAdded field
Echo.NewContextFunc func(pathParamAllocSize int) EditableContextfunction called to create new context instance. Allows creation of custom context implementationsAdded field
Echo.Filesystem fs.FSis used bycontext.File(),echo.File()andecho.Static()to serve files from given filesystem (embedded or not). Defaults toos.DirFS(".")current directory.Removed field
Echo.ListenerNetwork. Now part ofecho.StartConfigas fieldListenerNetworkRemoved field
Echo.HidePort. Now part ofecho.StartConfigas fieldHidePortRemoved field
Echo.HideBanner. Now part ofecho.StartConfigas fieldHideBannerRemoved field
Echo.DisableHTTP2. Now part ofecho.StartConfigas fieldDisableHTTP2Removed field
Echo.AutoTLSManager. AutoTLS is now started withecho.StartConfig.StartAutoTLS(). Can not be directly passed anymore. Create customhttp.Serverto have same functionality.Removed field
Echo.TLSListener. Now part ofecho.StartConfig. TLS can be configured withStartConfig.TLSConfigFunccallbackRemoved field
Echo.Listener. Replaced withecho.StartConfigimplementation. Can not be directly passed anymore. Create customhttp.Serverto have same functionality.Removed field
Echo.TLSServer. Replaced withecho.StartConfigimplementation. Can not be directly passed anymore. Create customhttp.Serverto have same functionality.Removed field
Echo.Server. Replaced withecho.StartConfigimplementation. Can not be directly passed anymore.Removed field
Echo.notFoundHandler.Removed field
Echo.colorer. No colored logger messages anymore. Removed as it is not useful in production env.Removed field
Echo.StdLogger. Now part ofecho.StartConfigRemoved field
Echo.startupMutex. Removed as server functionality is inecho.StartConfigstruct now.Changed
Echo.Router()returns nowRouterinterface instead of*Routerstruct.Changed
Echo.Routers()returns nowmap[string]Routerinstead ofmap[string]*Router.Added
Echo.RouterFor(host string) Routerto get vhost Router instance by its hostname.Added
Echo.ResetRouterCreator(creator func(e *Echo) Router)to allow users set custom callback to use/create customRouter implementations. This allows you to change router that Echo is using.
Moved Echo method
Echo.DefaultHTTPErrorHandler(err error, c Context)to be separate function that is created withDefaultHTTPErrorHandler(exposeError bool) HTTPErrorHandlerfunction. Note functionility thate.Debugprovided is now available withexposeError boolargument.Changed Echo route adding method signatures to return immutable
RouteInfoinstead of reference to added route.Now only way to add route with predefined name is:
Echo.CONNECTreturns nowRouteInfoinstead of*Route. Now:CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoEcho.DELETEreturns nowRouteInfoinstead of*Route. Now:DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoEcho.GETreturns nowRouteInfoinstead of*Route. Now:GET(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoEcho.HEADreturns nowRouteInfoinstead of*Route. Now:HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoEcho.OPTIONSreturns nowRouteInfoinstead of*Route. Now:OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoEcho.PATCHreturns nowRouteInfoinstead of*Route. Now:PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoEcho.POSTreturns nowRouteInfoinstead of*Route. Now:POST(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoEcho.PUTreturns nowRouteInfoinstead of*Route. Now:PUT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoEcho.TRACEreturns nowRouteInfoinstead of*Route. Now:TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoEcho.Anyreturns now[]RouteInfoinstead of[]*Route. Now:Any(path string, h HandlerFunc, m ...MiddlewareFunc) []RouteInfoEcho.Matchreturns now[]RouteInfoinstead of[]*Route. Now:Match(path string, h HandlerFunc, m ...MiddlewareFunc) []RouteInfoEcho.Filereturns nowRouteInfoinstead of*Route. Now:File(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoEcho.Addreturns nowRouteInfoinstead of*Route. Now:Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfoAdded
Echo.AddRoute(route Routable) (RouteInfo, error)which allows adding route usingecho.Routestructure orRoutableinterfaceand to handle invalid routes with error instead of panic as other method do.
Changed
Echo.StaticreturnsRouteInfoand change to accept middlewares as arguments. NOW:Static(prefix, root string, middleware ...MiddlewareFunc) RouteInfoAdded
echo.StaticDirectoryHandler(root string, disablePathUnescaping bool)to allow creating custom static assets serving paths.These two are identical:
Handler uses
echo.Context.File()to serve files and thereforeecho.Echo.Filesystemfield is used.Removed
Echo.Routes() []*Route. Equivalent ise.Router().Routes()Removed
Echo.Reverse(name string, params ...interface{}) string. Equivalent ise.Router().Routes().Reverse("routeName", 123)Removed
Echo.URI(handler HandlerFunc, params ...interface{}) string. Equivalent same asReverseRemoved
Echo.URL(h HandlerFunc, params ...interface{}) string. Equivalent same asReverseAll method related to starting
http.Serverhave been moved new implementationecho.StartConfigstructRemoved
Echo.Shutdown(ctx stdContext.Context) error. When usingStartConfigstarted server it can be shutdown withStartConfig.GracefulShutdownstruct that can havecontext.Contextwhich closing will close server.Removed
Echo.Close() error. When usingStartConfigstarted server it can be shutdown withStartConfig.GracefulShutdownstruct that can havecontext.Contextwhich closing will close server.Removed
Echo.TLSListenerAddr() net.Addr. To get listener address whenStartConfigis started use callbackStartConfig.ListenerAddrFunc func(addr net.Addr)which allows to access listener before server is started.Removed
Echo.ListenerAddr() net.Addr. To get listener address whenStartConfigis started use callbackStartConfig.ListenerAddrFunc func(addr net.Addr)which allows to access listener before server is started.Removed
Echo.StartServer(s *http.Server) (err error). Equivalent would be using callbackStartConfig.BeforeServeFunc func(s *http.Server) errorand starting server withStartConfig.Start(e)or usinghttp.Serverdirectly.Removed
Echo.StartH2CServer(address string, h2s *http2.Server) (err error), replace withStartConfig.StartH2CServer(e *Echo, h2s *http2.Server) errorRemoved
Echo.StartAutoTLS(address string) error, replaced withStartConfig.StartAutoTLS(e *Echo) errorRemoved
Echo.StartTLS(address string, certFile, keyFile interface{}) (err error), replace withStartConfig.StartTLS(e *Echo, certFile, keyFile interface{}) errorOnly
Echo.Start(address string) errorwas left in place for creating short demos/poc/examples.StartConfig.Start()ctrl-cto shutdown the server (note:Echo.Shutdownis removed)Echo supports serving requests with custom
echo.Contextimplementations. Setup context creation callback withEcho.NewContextFuncand whenrequest is being served and context being borrowed from the context pool, then context will be created by that callback.
Note: Using custom context is slightly slower than default context as cast to interface is slightly slower than to struct.
Removed support for custom
tcpKeepAliveListenerfor setting TCP keep-alive timeouts. From Go 1.13 this can be configured as:echo.Grouphas similar changes asecho.EchoGroup.CONNECTreturns nowRouteInfoinstead of*Route. Now:CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoGroup.DELETEreturns nowRouteInfoinstead of*Route. Now:DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoGroup.GETreturns nowRouteInfoinstead of*Route. Now:GET(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoGroup.HEADreturns nowRouteInfoinstead of*Route. Now:HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoGroup.OPTIONSreturns nowRouteInfoinstead of*Route. Now:OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoGroup.PATCHreturns nowRouteInfoinstead of*Route. Now:PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoGroup.POSTreturns nowRouteInfoinstead of*Route. Now:POST(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoGroup.PUTreturns nowRouteInfoinstead of*Route. Now:PUT(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoGroup.TRACEreturns nowRouteInfoinstead of*Route. Now:TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) RouteInfoGroup.Anyreturns now[]RouteInfoinstead of[]*Route. Now:Any(path string, h HandlerFunc, m ...MiddlewareFunc) []RouteInfoGroup.Matchreturns now[]RouteInfoinstead of[]*Route. Now:Match(path string, h HandlerFunc, m ...MiddlewareFunc) []RouteInfoGroup.Addreturns nowRouteInfoinstead of*Route. Now:Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfoGroup.AddRoute(route Routable) (RouteInfo, error)which allows adding route usingecho.Routestructure orRoutableinterface.Group.Staticreturns error and change to accept middlewares as arguments. NOW:Static(prefix, root string, middleware ...MiddlewareFunc) RouteInfoGroup.Filereturns error and change to accept middlewares as arguments. NOW:File(path, file string, middleware ...MiddlewareFunc) RouteInfoecho.Contextinterface has multiple breaking changes.Added
RouteMatchType() RouteMatchTypewhich helps middlewares to understand if this handler chain execution has handler at the end of something else (404/405). ForPremiddleware this valuereturns always "unknown" as
Premiddleware is executed before router tries to match the request.Basically enum with values: "route match/not found/method not allowed/unknown"
Added
RouteInfo() RouteInfoto return route info to which this request was matched to. AsRouteInfois interface then users can create custom implementationthat can be added to router through
echo.Echo.AddRoute(Routable)method.Routableis interface that is responsible of creatingRouteInfoinside router when route is being added.Renamed
Param(name string) stringtoPathParam(name string) string.Renamed
ParamNames() []stringtoPathParams() PathParamsRenamed
SetParamNames(names ...string)toSetPathParams(params PathParams)Reasoning for that is: Method name
Paramis too ambiguous. Context interface already has methods like:which explicitly describe where that
*Paramor*Valuedata comes/originates from.PathParamis explicit as those methods.Removed
ParamValues() []stringasPathParamsresult contains both name and value inPathParamstructRemoved
Logger() Logger. Usage of Echo own logger is disgouraged and use whatever logger library you choose and if needed put it into context withe.Set()and fetch withe.Get()Removed
SetLogger(l Logger)Removed
Handler()method.Removed
SetHandler()method.Move to
echo.EditableContextSetParamValues(values ...string)SetHandler(h HandlerFunc)Note:
EditableContextinterface is only for Echo internal usage to setup Context after route match has been found, just before handler chain will be called. Contains setters that should not be touched in middleware or handler.Note: internally Context now 2 distinct fields to hold path parameters.
context.pathParamslifecycle (allocation) is handled by Echo to reduce allocation. This field is not directly accessible to user.context.currentParamsis meant for cases when middlewares are mutating path params and get copy ofpathParamsvalues on first usage. This field is settable for user.echo.contextstruct.context.File(file string)now usesecho.Filesystemto serve file. So now you can use embedded Fs to serve files.context.FsFile(file string, filesystem fs.FS) errorcan be used to serve file from filesystem.Router
Route(r) interfaces
Introduced interface for router. This will allow using custom router implementations with Echo.
Routable is interface for registering Route with Router. During route registration process the Router will convert
Routable to RouteInfo with ToRouteInfo method. By creating custom implementation of Routable additional information
about registered route can be stored in Routes (i.e. privileges used with route etc.)
RouteInfo interface:
So when you add route with
Echo.AddRoute(route Routable) errorthat route is added to router withAdd(routable Routable)andRouteInfoof thatroute (which is created by
Routable.ToRouteInfo()method) is accessible fromrouter.Routes(). This all means that you can pass in your own custom types(than can have extra information about route included in that type) and you are able to have your own routeinfo implementations when you access
ask for route list with
e.Router().Routes().Other router changes
RouterConfig.unescapePathParamValueswill instructDefaultRouterto unescape path parameter values for matched route. People did this with middlewares and possible messed up maxParams size with that.RouterConfig.allowOverwritingRoutewill instructDefaultRouter(not to) to generate error when duplicate route (method+path) is addedGET /users/:idandPOST /users/:userIDLogger
Logger is trimmed down and used only for logging Echo internal stuff and/or used as
http.Server.Errorlogfield for capturinghttp server logged errors. For logging in handlers/middlewares use logger library of your own choosing.
Starting http server with Echo
All http server related methods and fields are moved from
echo.Echostruct to separate implementationecho.StartConfigWhich has the following methods to replace ones that were removed from
echo.Echo:StartTLS(e *Echo, certFile, keyFile interface{}) errorStartAutoTLS(e *Echo) errorQuick example:
New config struct fields are following:
Binder
e.Bind()andDefaultBinderto be precise do not clear values when binding for base types (ints, bool, float). See Empty string turns into "false" bool during binding #1521opts.Lengthwould be0after bind if that field did not exists in query. Now it stays100(value is not touched).Middlewares
General
Existing creator functions stay as they are - same signature and panicing on invalid configuration.
BasicAuth
DefaultBasicAuthConfigstruct. Middleware creator func will set now default values.BasicAuthConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create basic auth middleware without panics.BodyDump
DefaultBodyDumpConfigstruct. Middleware creator func will set now default values.BodyDumpConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create body dump middleware without panics.BodyLimit
DefaultBodyLimitConfigstruct. Middleware creator func will set now default values.BodyLimitConfig.LimitBytesfromstringtoint64(allowed size in bytes).BodyLimitConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create body limit middleware without panics.Gzip
DefaultGzipConfigstruct. Middleware creator func will set now default values.GzipConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create Gzip middleware without panics.CORS
CORSConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create CORS middleware without panics.CSRF
CSRFConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create CSRF middleware without panics.Decompress
DefaultDecompressConfigstruct. Middleware creator func will set now default values.DecompressConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create decompress middleware without panics.JWT
JWT middleware was refactored not to depend any JWT library. To use JWT user must provide own token extraction method.
Changed all methods that extract raw token from request to support returning multiple values. To support cases when
browser sends multiple
authorizationheaders (ala request has basic auth + bearer headers). Previously whatever wasfirst was extracted which could be not intended value to be parsed as JWT token.
Changed cases when no token was found/extracted (
ErrJWTMissing) to returnhttp.StatusUnauthorized 401status code instead ofhttp.StatusBadRequest 400Renamed
ErrorHandlerWithContexttoErrorHandler. Signatures isJWTErrorHandlerWithContext func(error, echo.Context) errorChanged middleware to resume handler chain execution
next(c)when developer providedJWTConfig.ErrorHandler()callback decides to swallow the given errorThis is Useful in cases when portion of your site/api is publicly accessible and has extra features for authorized users.
In that case you can use
ErrorHandlerto set default public token to request and continue with handler chain by returning no error.Removed configuration fields related to specific JWT token parsing implementations
JWTConfig.SigningKeyfield.JWTConfig.SigningKeysfield.JWTConfig.SigningMethodfield.JWTConfig.Claimsfield.Added example in
jwt_external_test.gohow to use JWT library withgolang-jwt/jwtlibrary.Middleware is to be created as:
Added
JWTConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create JWT middleware without panics.KeyAuth
KeyAuthConfig.AuthSchemefield. UseKeyAuthConfig.KeyLookup = "header:Authorization:Bearer "instead (NB: space at the end is important).KeyAuthConfig.KeyLookupto support additional extraction sources:browser sends multiple
authorizationheaders (ala request has basic auth + bearer headers). Previously whatever wasfirst was extracted which could be not intended value to be checked/validated as key auth.
KeyAuthConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create key auth middleware without panics.Logger
c.Error()and return error to be handled up in caller chain (or global error handler)LoggerConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create logger middleware without panics.MethodOverride
MethodOverrideConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create method override middleware without panics.Proxy
ProxyConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create proxy middleware without panics.RateLimiter
RateLimiterConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create rate limiter middleware without panics.Recover
RecoverConfig.LogLevelfield.c.Error()andc.Logger(). Recovered error/value will bubble up and be handledeventually in global error handler.
RecoverConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create recover middleware without panics.RequestID
DefaultRequestIDConfigstructRequestIDConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create request ID middleware without panics.Redirect
RedirectConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create redirect middleware without panics.Rewrite
RewriteConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create redirect middleware without panics.Secure
SecureConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create secure middleware without panics.(Add/Remove)trailing slash
TrailingSlashConfigtoAddTrailingSlashConfigandRemoveTrailingSlashConfigAddTrailingSlashConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create add trailing slash middleware without panics.RemoveTrailingSlashConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create remove trailing slash middleware without panics.Static
StaticConfig.Filesystemfield which will befs.FSused to serve file. Defaults toecho.Echo.Filesystemvalue.StaticConfig.DisablePathUnescapingfield disable path escaping when serving the file.StaticConfig.DirectoryListTemplatefield to allow developer to specify custom html template for directory listings.StaticConfig.ToMiddleware() (echo.MiddlewareFunc, error)to create static middleware without panics.Timeout
TODO: propose to delete this middleware.
Benchmarks
TODO: paste benchstats results
Beta Was this translation helpful? Give feedback.
All reactions