### Update Server Startup Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Demonstrates the transition from simple Start methods to using StartConfig for advanced features like graceful shutdown with context. ```go ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) defer cancel() sc := echo.StartConfig{Address: ":8080"} sc.Start(ctx, e) ``` -------------------------------- ### Basic Echo Server Example Source: https://github.com/labstack/echo/blob/master/README.md A simple Echo server with RequestLogger and Recover middleware. Demonstrates defining a root route and starting the server. Logs startup errors using slog. ```go package main import ( "github.com/labstack/echo/v5" "github.com/labstack/echo/v5/middleware" "log/slog" "net/http" ) func main() { // Echo instance e := echo.New() // Middleware e.Use(middleware.RequestLogger()) // use the RequestLogger middleware with slog logger e.Use(middleware.Recover()) // recover panics as errors for proper error handling // Routes e.GET("/", hello) // Start server if err := e.Start(":8080"); err != nil { slog.Error("failed to start server", "error", err) } } // Handler func hello(c *echo.Context) error { return c.String(http.StatusOK, "Hello, World!") } ``` -------------------------------- ### Install Echo Framework Source: https://github.com/labstack/echo/blob/master/README.md Install the latest major version of the Echo framework using the go get command. Ensure your Go version is compatible with the latest Echo release. ```sh // go get github.com/labstack/echo/{version} go get github.com/labstack/echo/v5 ``` -------------------------------- ### Server Startup Configuration in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md The `StartConfig` struct provides comprehensive options for configuring Echo server startup. It includes settings for address, TLS, graceful shutdown timeouts, and callback functions for server events. The `Start` and `StartTLS` methods initiate the server with the specified configuration. ```go type StartConfig struct { Address string HideBanner bool HidePort bool CertFilesystem fs.FS TLSConfig *tls.Config ListenerNetwork string ListenerAddrFunc func(addr net.Addr) GracefulTimeout time.Duration OnShutdownError func(err error) BeforeServeFunc func(s *http.Server) error } func (sc StartConfig) Start(ctx context.Context, h http.Handler) error func (sc StartConfig) StartTLS(ctx context.Context, h http.Handler, certFile, keyFile any) error ``` ```go // v5 - More control over server startup ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defuncel cancel() sc := echo.StartConfig{ Address: ":8080", GracefulTimeout: 10 * time.Second, } if err := sc.Start(ctx, e); err != nil { log.Fatal(err) } ``` -------------------------------- ### Migration Guide Summary Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Provides a summary of the migration steps from Echo v4 to v5, including automated commands and manual code updates. ```APIDOC ## Migration Guide Summary ### Automated Migration Steps (Linux) If you are using Linux, you can use the following commands to automate parts of the migration: ```bash find . -type f -name "*.go" -exec sed -i 's/ echo.Context/ *echo.Context/g' {} + find . -type f -name "*.go" -exec sed -i 's/echo\/v4/echo\/v5/g' {} + ``` Alternatively, perform these replacements in your IDE. ### Manual Code Updates 1. **Update All Handler Signatures** *Before* ```go func MyHandler(c echo.Context) error { ... } ``` *After* ```go func MyHandler(c *echo.Context) error { ... } ``` 2. **Update Logger Usage** *Before* ```go e.Logger.Info("Server started") c.Logger().Error("Something went wrong") ``` *After* ```go e.Logger.Info("Server started") c.Logger().Error("Something went wrong") // Same API, different logger ``` 3. **Use Type-Safe Parameter Extraction** *Before* ```go idStr := c.Param("id") id, err := strconv.Atoi(idStr) ``` *After* ```go id, err := echo.PathParam[int](c, "id") ``` ``` -------------------------------- ### Structured Path Value Handling in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Defines `PathValue` and `PathValues` types for structured handling of URL path parameters. Includes methods to get parameter values by name, with or without a default. Also provides context methods to access and set these path values. ```go type PathValue struct { Name string Value string } type PathValues []PathValue func (p PathValues) Get(name string) (string, bool) func (p PathValues) GetOr(name string, defaultValue string) string // Context methods func (c *Context) PathValues() PathValues func (c *Context) SetPathValues(pathValues PathValues) ``` -------------------------------- ### Route Registration Return Type Change (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Shows the modification in return types for route registration methods like GET and Any in Echo v5. They now return `RouteInfo` instead of `*Route`, and `Routes` is a new collection type. ```go package main import ( "github.com/labstack/echo/v4" ) // v4 example (conceptual) // func (e *echo.Echo) GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route // v5 example func (e *echo.Echo) GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) echo.RouteInfo { // Implementation returns RouteInfo return echo.RouteInfo{} } func (e *echo.Echo) Any(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) echo.Routes { // Implementation returns Routes collection return echo.Routes{} } // New Types in v5 type RouteInfo struct { Name string Method string Path string Parameters []string } type Routes []RouteInfo ``` -------------------------------- ### Migrate Echo Instance Methods Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Demonstrates the change in return types for route registration and static file serving, moving from pointers to RouteInfo structures. ```go // v5 Route Registration func (e *Echo) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfo func (e *Echo) AddRoute(route Route) (RouteInfo, error) // v5 Static File Serving func (e *Echo) Static(pathPrefix, fsRoot string, middleware ...MiddlewareFunc) RouteInfo ``` -------------------------------- ### Router Interface and Methods (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Presents the structure and methods of the Router in Echo v4. This includes its initialization, adding routes, finding routes, reversing paths, and listing all defined routes. ```go type Router struct { ... } func NewRouter(e *Echo) *Router func (r *Router) Add(method, path string, h HandlerFunc) func (r *Router) Find(method, path string, c Context) func (r *Router) Reverse(name string, params ...interface{}) string func (r *Router) Routes() []*Route ``` -------------------------------- ### Echo Constructor with Configuration in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Introduces `NewWithConfig` which allows creating an Echo instance using a `Config` struct. This provides a way to set up Echo's internal components like logger, binder, and renderer during initialization, preventing mutation after creation. ```go type Config struct { // Configuration for Echo (logger, binder, renderer, etc.) } func NewWithConfig(config Config) *Echo ``` -------------------------------- ### Access Path Parameters Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Demonstrates the new way to access path parameters using PathValues instead of separate name and value slices. ```go pathValues := c.PathValues() for _, pv := range pathValues { fmt.Println(pv.Name, pv.Value) } ``` -------------------------------- ### Time Parsing Options in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Introduces `TimeLayout` and `TimeOpts` for flexible time parsing. `TimeLayout` defines constants for different Unix time formats (seconds, milliseconds, nanoseconds). `TimeOpts` allows specifying the layout and target time locations for parsing. ```go type TimeLayout string const ( TimeLayoutUnixTime = TimeLayout("UnixTime") TimeLayoutUnixTimeMilli = TimeLayout("UnixTimeMilli") TimeLayoutUnixTimeNano = TimeLayout("UnixTimeNano") ) type TimeOpts struct { Layout TimeLayout ParseInLocation *time.Location ToInLocation *time.Location } ``` -------------------------------- ### Echo Instance Method Changes (v4 vs v5) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Compares route registration, static file serving, server management, and router access methods between Echo v4 and v5. ```APIDOC ## Echo Instance Method Changes (v4 vs v5) ### Route Registration #### v4 ```go func (e *Echo) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route ``` #### v5 ```go func (e *Echo) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) RouteInfo func (e *Echo) AddRoute(route Route) (RouteInfo, error) // NEW ``` ### Static File Serving #### v4 ```go func (e *Echo) Static(pathPrefix, fsRoot string) *Route func (e *Echo) StaticFS(pathPrefix string, filesystem fs.FS) *Route func (e *Echo) File(path, file string, m ...MiddlewareFunc) *Route func (e *Echo) FileFS(path, file string, filesystem fs.FS, m ...MiddlewareFunc) *Route ``` #### v5 ```go func (e *Echo) Static(pathPrefix, fsRoot string, middleware ...MiddlewareFunc) RouteInfo func (e *Echo) StaticFS(pathPrefix string, filesystem fs.FS, middleware ...MiddlewareFunc) RouteInfo func (e *Echo) File(path, file string, middleware ...MiddlewareFunc) RouteInfo func (e *Echo) FileFS(path, file string, filesystem fs.FS, m ...MiddlewareFunc) RouteInfo ``` *Return type changed from `*Route` to `RouteInfo`.* ### Server Management #### v4 ```go func (e *Echo) Start(address string) error func (e *Echo) StartTLS(address string, certFile, keyFile interface{}) error func (e *Echo) StartAutoTLS(address string) error func (e *Echo) StartH2CServer(address string, h2s *http2.Server) error func (e *Echo) StartServer(s *http.Server) error func (e *Echo) Shutdown(ctx context.Context) error func (e *Echo) Close() error func (e *Echo) ListenerAddr() net.Addr func (e *Echo) TLSListenerAddr() net.Addr func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) ``` #### v5 ```go func (e *Echo) Start(address string) error // Simplified func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request) ``` *Removed: `StartTLS`, `StartAutoTLS`, `StartH2CServer`, `StartServer`. Use `StartConfig` instead for advanced server configuration.* *Removed: `Shutdown`, `Close`, `ListenerAddr`, `TLSListenerAddr`.* *Removed: `DefaultHTTPErrorHandler` (now a top-level factory function).* *v5 provides `StartConfig` type for all advanced server configuration.* ### Router Access #### v4 ```go func (e *Echo) Router() *Router func (e *Echo) Routers() map[string]*Router // For multi-host func (e *Echo) Routes() []*Route func (e *Echo) Reverse(name string, params ...interface{}) string func (e *Echo) URI(handler HandlerFunc, params ...interface{}) string func (e *Echo) URL(h HandlerFunc, params ...interface{}) string func (e *Echo) Host(name string, m ...MiddlewareFunc) *Group ``` #### v5 ```go func (e *Echo) Router() Router // Returns interface ``` *Removed: `Routers()`, `Reverse()`, `URI()`, `URL()`, `Host()`.* *Use `router.Routes()` and `Routes.Reverse()` instead.* ``` -------------------------------- ### Virtual Host Support in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Introduces `NewVirtualHostHandler` which enables the creation of an Echo instance that can route incoming requests to different Echo instances based on the request's host header. This is useful for managing multiple subdomains or virtual hosts within a single application. ```go func NewVirtualHostHandler(vhosts map[string]*Echo) *Echo ``` -------------------------------- ### Context Store Helpers Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Type-safe helpers for retrieving values from the context, updated to accept *Context. ```go user, err := echo.ContextGet[*User](c, "user") count, err := echo.ContextGetOr[int](c, "count", 0) ``` -------------------------------- ### Context Store Helpers (v5) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Describes the type-safe context value retrieval functions in Echo v5, which now accept `*Context`. ```APIDOC ## Context Store Helpers Now Use `*Context` ```go // Type-safe context value retrieval func ContextGet[T any](c *Context, key string) (T, error) func ContextGetOr[T any](c *Context, key string, defaultValue T) (T, error) // Error types var ErrNonExistentKey = errors.New("non existent key") var ErrInvalidKeyType = errors.New("invalid key type") ``` These helpers existed in v4 with `Context` and now accept `*Context`. **Example:** ```go // v5 user, err := echo.ContextGet[*User](c, "user") count, err := echo.ContextGetOr[int](c, "count", 0) ``` ``` -------------------------------- ### New Context Methods in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Adds several new methods to the `Context` type for enhanced request handling. These include serving files from a filesystem, retrieving form values or parameters with default values, initializing route information, and accessing route details. ```go // v5 additions func (c *Context) FileFS(file string, filesystem fs.FS) error func (c *Context) FormValueOr(name, defaultValue string) error func (c *Context) InitializeRoute(ri *RouteInfo, pathValues *PathValues) func (c *Context) ParamOr(name, defaultValue string) string func (c *Context) QueryParamOr(name, defaultValue string) string func (c *Context) RouteInfo() RouteInfo ``` -------------------------------- ### New echotest Package Utilities in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md The `echotest` package in v5 offers utilities for testing Echo applications. It includes functions like `LoadBytes` for loading test fixtures and `TrimNewlineEnd` for data manipulation, along with configuration types for test contexts and multipart forms. ```go package echotest // import "github.com/labstack/echo/v5/echotest" func LoadBytes(t *testing.T, name string, opts ...loadBytesOpts) []byte func TrimNewlineEnd(bytes []byte) []byte type ContextConfig struct{ ... } type MultipartForm struct{ ... } type MultipartFormFile struct{ ... } ``` -------------------------------- ### Router Interface and RouteInfo Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Covers the new Router interface and the transition from *Route to RouteInfo for route registration. ```APIDOC ## Router and Route Registration ### Description Echo v5 introduces a `Router` interface and a `DefaultRouter` implementation. Route registration methods now return `RouteInfo` instead of `*Route`. ### RouteInfo Structure - **Name** (string) - Route name - **Method** (string) - HTTP method - **Path** (string) - Route path - **Parameters** ([]string) - List of path parameters ### Example ```go // Registration now returns RouteInfo routeInfo := e.GET("/users", userHandler) ``` ``` -------------------------------- ### Access Response Object Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Shows how to access response headers and unwrap the underlying echo.Response object. ```go c.Response().Header().Set("X-Custom", "value") resp, err := echo.UnwrapResponse(c.Response()) ``` -------------------------------- ### Renderer Interface Updates (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Highlights the changes in the Renderer interface between Echo v4 and v5. The primary change is the reordering of parameters, placing the context object first in v5. ```go // v4 type Renderer interface { Render(io.Writer, string, interface{}, Context) error } // v5 type Renderer interface { Render(c *Context, w io.Writer, templateName string, data any) error } ``` -------------------------------- ### v5 Router Interface and DefaultRouter Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Details the new Router interface and its concrete implementation, DefaultRouter, along with configuration options. ```APIDOC ## Router Interface and DefaultRouter ### Description This section describes the `Router` interface and the `DefaultRouter` implementation in Echo v5. It highlights key methods and configuration options. ### Router Interface ```go type Router interface { Add(routable Route) (RouteInfo, error) Remove(method string, path string) error Routes() Routes Route(c *Context) HandlerFunc } ``` ### DefaultRouter Struct ```go type DefaultRouter struct { ... } ``` ### Constructor Functions ```go func NewRouter(config RouterConfig) *DefaultRouter func NewConcurrentRouter(r Router) Router ``` ### Router Configuration (`RouterConfig`) ```go type RouterConfig struct { NotFoundHandler HandlerFunc MethodNotAllowedHandler HandlerFunc OptionsMethodHandler HandlerFunc AllowOverwritingRoute bool UnescapePathParamValues bool UseEscapedPathForMatching bool } ``` ### Key Changes from v4: - Router is now an interface. - `DefaultRouter` is the concrete implementation. - `Add()` now returns `(RouteInfo, error)`. - New `Remove()` method for removing routes. - New `Route()` method replaces the old `Find()` method. - Configuration is managed through `RouterConfig`. ``` -------------------------------- ### Update Group Route Registration Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Group methods like File, Static, and StaticFS now return RouteInfo and accept optional middleware functions in v5. ```go // v5 func (g *Group) File(path, file string, middleware ...MiddlewareFunc) RouteInfo func (g *Group) Static(pathPrefix, fsRoot string, middleware ...MiddlewareFunc) RouteInfo func (g *Group) StaticFS(pathPrefix string, filesystem fs.FS, middleware ...MiddlewareFunc) RouteInfo ``` -------------------------------- ### Logger Interface Change (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Demonstrates the shift from Echo's custom Logger interface to Go's standard `log/slog` package in v5. This change necessitates updating all logging-related code to use the new structured logger. ```go package main import ( "log/slog" "github.com/labstack/echo/v4" ) // v4 example (conceptual) // type Logger interface { // Print(args ...interface{}) // // ... other methods // } // v5 example func (c *echo.Context) Logger() *slog.Logger { // Implementation returns standard library logger return slog.Default() } func (c *echo.Context) SetLogger(logger *slog.Logger) { // Implementation to set the logger } ``` -------------------------------- ### Middleware Signature and Type Updates (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Details various updates to middleware signatures and types in Echo v5 compared to v4. This includes changes in parameter types (e.g., *echo.Context), optional parameters, and configuration structures. ```go // CORS now accepts optional allow-origins func CORS(allowOrigins ...string) echo.MiddlewareFunc // BodyLimit now accepts bytes func BodyLimit(limitBytes int64) echo.MiddlewareFunc // DefaultSkipper now uses *echo.Context func DefaultSkipper(c *echo.Context) bool // Trailing slash configs renamed/split func AddTrailingSlashWithConfig(config AddTrailingSlashConfig) echo.MiddlewareFunc func RemoveTrailingSlashWithConfig(config RemoveTrailingSlashConfig) echo.MiddlewareFunc type AddTrailingSlashConfig struct{ ... } type RemoveTrailingSlashConfig struct{ ... } // Auth + extractor signatures now use *echo.Context and add ExtractorSource type BasicAuthValidator func(c *echo.Context, user string, password string) (bool, error) type Extractor func(c *echo.Context) (string, error) type ExtractorSource string type KeyAuthValidator func(c *echo.Context, key string, source ExtractorSource) (bool, error) type KeyAuthErrorHandler func(c *echo.Context, err error) error // BodyDump handler now includes err type BodyDumpHandler func(c *echo.Context, reqBody []byte, resBody []byte, err error) // ValuesExtractor now returns extractor source and CreateExtractors takes a limit type ValuesExtractor func(c *echo.Context) ([]string, ExtractorSource, error) func CreateExtractors(lookups string, limit uint) ([]ValuesExtractor, error) type ValueExtractorError struct{ ... } // New constants const KB = 1024 // Rate limiter store now takes a float64 limit func NewRateLimiterMemoryStore(rateLimit float64) (store *RateLimiterMemoryStore) ``` -------------------------------- ### Automated Migration Commands Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Shell commands to perform bulk replacements for package imports and context pointer types during migration. ```bash find . -type f -name "*.go" -exec sed -i 's/ echo.Context/ *echo.Context/g' {} + find . -type f -name "*.go" -exec sed -i 's/echo\/v4/echo\/v5/g' {} + ``` -------------------------------- ### Generic Parameter Extraction Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Updated generic helpers for extracting query, path, and form parameters. These now accept *Context and use the FormValue naming convention. ```go id, err := echo.PathParam[int](c, "id") page, err := echo.QueryParamOr[int](c, "page", 1) tags, err := echo.QueryParams[string](c, "tags") ``` -------------------------------- ### Generate Certificate and Private Key with OpenSSL Source: https://github.com/labstack/echo/blob/master/_fixture/certs/README.md Generates a self-signed SSL/TLS certificate and a private key. This command is suitable for development or testing environments. It creates a certificate valid for 9999 days with RSA 4096-bit encryption and includes localhost in the subject alternative names. ```bash openssl req -x509 -newkey rsa:4096 -sha256 -days 9999 -nodes \ -keyout key.pem -out cert.pem -subj "/CN=localhost" \ -addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1" ``` -------------------------------- ### Router Implementation Change (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Highlights the changes in Echo's Router implementation between v4 and v5. v5 introduces a `Router` interface and a `DefaultRouter` concrete type, with `NewRouter` now accepting `RouterConfig`. ```go package main import ( "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) // v4 example (conceptual) // func NewRouter(e *echo.Echo) *Router { ... } // func (e *echo.Echo) Router() *Router { ... } // v5 example // type Router interface { ... } // type DefaultRouter struct { ... } // func NewRouter(config echo.RouterConfig) *DefaultRouter { ... } // func (e *echo.Echo) Router() echo.Router { ... } // Example of using NewRouter in v5 func setupRouter() echo.Router { config := echo.RouterConfig{ // ... router configuration options } return echo.NewRouter(config) } ``` -------------------------------- ### NewContext Changes Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Details the changes in context creation and response handling between Echo v4 and v5. ```APIDOC ## NewContext Changes ### v4 ```go func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) Context func NewResponse(w http.ResponseWriter, e *Echo) *Response ``` ### v5 ```go func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) *Context func NewContext(r *http.Request, w http.ResponseWriter, opts ...any) *Context // Standalone func NewResponse(w http.ResponseWriter, logger *slog.Logger) *Response ``` ``` -------------------------------- ### Type-Safe Parameter Extraction Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Shows the new idiomatic way to extract and convert path parameters using generics in Echo v5. ```go // After id, err := echo.PathParam[int](c, "id") ``` -------------------------------- ### Added Middleware Exports in Echo v5 (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Lists new middleware-related exports available in Echo v5. This includes predefined HTTP error variables and redirect configuration structures. ```go var ErrInvalidKey = echo.NewHTTPError(http.StatusUnauthorized, "invalid key") var ErrKeyMissing = echo.NewHTTPError(http.StatusUnauthorized, "missing key") var RedirectHTTPSConfig = RedirectConfig{ ... } var RedirectHTTPSWWWConfig = RedirectConfig{ ... } var RedirectNonHTTPSWWWConfig = RedirectConfig{ ... } var RedirectNonWWWConfig = RedirectConfig{ ... } var RedirectWWWConfig = RedirectConfig{ ... } ``` -------------------------------- ### Define Router Interface and Configuration Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Defines the new Router interface and configuration structure introduced in Echo v5 to allow for more flexible routing implementations. ```go type Router interface { Add(routable Route) (RouteInfo, error) Remove(method string, path string) error Routes() Routes Route(c *Context) HandlerFunc } type RouterConfig struct { NotFoundHandler HandlerFunc MethodNotAllowedHandler HandlerFunc OptionsMethodHandler HandlerFunc AllowOverwritingRoute bool UnescapePathParamValues bool UseEscapedPathForMatching bool } ``` -------------------------------- ### Middleware Configuration Interface in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Defines the `MiddlewareConfigurator` interface, which allows middleware configurations to be converted into `MiddlewareFunc` types. This promotes a safer way to handle middleware creation, avoiding panics. ```go type MiddlewareConfigurator interface { ToMiddleware() (MiddlewareFunc, error) } ``` -------------------------------- ### New Binder Functions in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Provides top-level functions for binding request data to Go structs. `BindBody`, `BindHeaders`, `BindPathValues`, and `BindQueryParams` simplify the process of extracting and validating data from different parts of an HTTP request directly using a `*Context`. ```go func BindBody(c *Context, target any) error func BindHeaders(c *Context, target any) error func BindPathValues(c *Context, target any) error // Renamed from BindPathParams func BindQueryParams(c *Context, target any) error ``` -------------------------------- ### Removed HTTP Method Constants in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md In v5, constants for HTTP methods like `CONNECT` that were deprecated in v4 have been removed. Developers are now expected to use the standard library's `http.Method*` constants directly for clarity and consistency. ```go // v4 - Removed in v5 const CONNECT = http.MethodConnect // Use http.MethodConnect directly // Reason: Deprecated in v4, use stdlib `http.Method*` constants instead. ``` -------------------------------- ### HandlerName Utility Function (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Introduces the HandlerName utility function, available exclusively in Echo v5. This function retrieves the name of a given HandlerFunc. ```go // v5 only func HandlerName(h HandlerFunc) string ``` -------------------------------- ### Update Binder Interface Signature Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md The Binder interface Bind method signature has been updated in v5, swapping the order of the Context and target parameters. ```go // v4 type Binder interface { Bind(i interface{}, c Context) error } // v5 type Binder interface { Bind(c *Context, target any) error } ``` -------------------------------- ### Update HTTPError Creation Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Reflects the simplified signature for creating new HTTP errors in Echo. ```go return echo.NewHTTPError(400, "invalid request") ``` -------------------------------- ### Update Custom Binder Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Updates the custom binder interface to use the new parameter order and the 'any' type for the target parameter. ```go type MyBinder struct{} func (b *MyBinder) Bind(c *echo.Context, target any) error { ... } ``` -------------------------------- ### Middleware Package Changes - Added Middleware Exports Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Lists new middleware-related exports introduced in v5. ```APIDOC ## Middleware Package Changes ### Added Middleware Exports - **Error Constants**: New `echo.NewHTTPError` constants for authentication. ```go var ErrInvalidKey = echo.NewHTTPError(http.StatusUnauthorized, "invalid key") var ErrKeyMissing = echo.NewHTTPError(http.StatusUnauthorized, "missing key") ``` - **Redirect Configurations**: New redirect configuration types. ```go var RedirectHTTPSConfig = RedirectConfig{ ... } var RedirectHTTPSWWWConfig = RedirectConfig{ ... } var RedirectNonHTTPSWWWConfig = RedirectConfig{ ... } var RedirectNonWWWConfig = RedirectConfig{ ... } var RedirectWWWConfig = RedirectConfig{ ... } ``` ``` -------------------------------- ### Check Certificate Details with OpenSSL Source: https://github.com/labstack/echo/blob/master/_fixture/certs/README.md Inspects the details of an SSL/TLS certificate. This command is useful for verifying certificate information such as issuer, subject, validity period, and cryptographic details. ```bash openssl x509 -in cert.pem -text ``` -------------------------------- ### HandlerName Utility Function (v5) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Introduces the new `HandlerName` utility function available only in v5. ```APIDOC ## HandlerName ### v5 only ```go func HandlerName(h HandlerFunc) string ``` **Description**: A new utility function `HandlerName` has been added in v5. It takes a `HandlerFunc` as input and returns its name as a string. ``` -------------------------------- ### Generic Parameter Extraction Functions (v5) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Details the updated signatures and functionality of generic parameter extraction functions in Echo v5, including query, path, and form parameters. ```APIDOC ## Generic Parameter Extraction Functions (v5) These helpers keep the same generic API but now accept `*Context`, and the form helpers are renamed from `FormParam*` to `FormValue*`: ```go // Query Parameters func QueryParam[T any](c *Context, key string, opts ...any) (T, error) func QueryParamOr[T any](c *Context, key string, defaultValue T, opts ...any) (T, error) func QueryParams[T any](c *Context, key string, opts ...any) ([]T, error) func QueryParamsOr[T any](c *Context, key string, defaultValue []T, opts ...any) ([]T, error) // Path Parameters func PathParam[T any](c *Context, paramName string, opts ...any) (T, error) func PathParamOr[T any](c *Context, paramName string, defaultValue T, opts ...any) (T, error) // Form Values func FormValue[T any](c *Context, key string, opts ...any) (T, error) func FormValueOr[T any](c *Context, key string, defaultValue T, opts ...any) (T, error) func FormValues[T any](c *Context, key string, opts ...any) ([]T, error) func FormValuesOr[T any](c *Context, key string, defaultValue []T, opts ...any) ([]T, error) // Generic Parsing func ParseValue[T any](value string, opts ...any) (T, error) func ParseValueOr[T any](value string, defaultValue T, opts ...any) (T, error) func ParseValues[T any](values []string, opts ...any) ([]T, error) func ParseValuesOr[T any](values []string, defaultValue []T, opts ...any) ([]T, error) ``` `FormParam*` was renamed to `FormValue*`; the rest keep names but now take `*Context`. **Supported Types:** - bool, string - int, int8, int16, int32, int64 - uint, uint8, uint16, uint32, uint64 - float32, float64 - time.Time, time.Duration - BindUnmarshaler, encoding.TextUnmarshaler, json.Unmarshaler **Example Usage:** ```go // v5 - Type-safe parameter binding id, err := echo.PathParam[int](c, "id") page, err := echo.QueryParamOr[int](c, "page", 1) tags, err := echo.QueryParams[string](c, "tags") ``` ``` -------------------------------- ### Router Interface Changes Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Provides details on the v4 Router concrete struct and its methods. ```APIDOC ## Router Interface Changes ### v4 Router (Concrete Struct) ```go type Router struct { ... } func NewRouter(e *Echo) *Router func (r *Router) Add(method, path string, h HandlerFunc) func (r *Router) Find(method, path string, c Context) func (r *Router) Reverse(name string, params ...interface{}) string func (r *Router) Routes() []*Route ``` **Description**: This section outlines the structure and methods of the `Router` concrete struct in v4 of the Echo framework. It includes functions for initialization, adding routes, finding routes, reversing routes, and retrieving all defined routes. ``` -------------------------------- ### JSONSerializer Interface Changes Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Illustrates the evolution of the JSONSerializer interface between v4 and v5, highlighting parameter type changes. ```APIDOC ## JSONSerializer Interface ### v4 ```go type JSONSerializer interface { Serialize(c Context, i interface{}, indent string) error Deserialize(c Context, i interface{}) error } ``` ### v5 ```go type JSONSerializer interface { Serialize(c *Context, target any, indent string) error Deserialize(c *Context, target any) error } ``` **Description**: The `JSONSerializer` interface in Echo has been updated between v4 and v5. In v5, the `Context` parameter type is now a pointer (`*Context`), and the types for the data being serialized/deserialized have been updated from `interface{}` to `any` for `Serialize` and `Deserialize` respectively. ``` -------------------------------- ### Enhanced Routing Features in Go Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Provides advanced routing capabilities including adding routes via `AddRoute`, accessing middleware lists, and managing routes as a collection. The `Routes` type offers filtering by method, name, or path, and finding specific routes. It also supports reversing paths to generate URLs. ```go // New route methods func (e *Echo) AddRoute(route Route) (RouteInfo, error) func (e *Echo) Middlewares() []MiddlewareFunc func (e *Echo) PreMiddlewares() []MiddlewareFunc type AddRouteError struct{ ... } // Routes collection with filters type Routes []RouteInfo func (r Routes) Clone() Routes func (r Routes) FilterByMethod(method string) (Routes, error) func (r Routes) FilterByName(name string) (Routes, error) func (r Routes) FilterByPath(path string) (Routes, error) func (r Routes) FindByMethodPath(method string, path string) (RouteInfo, error) func (r Routes) Reverse(routeName string, pathValues ...any) (string, error) // RouteInfo operations func (r RouteInfo) Clone() RouteInfo func (r RouteInfo) Reverse(pathValues ...any) string ``` -------------------------------- ### Removed/Consolidated Middleware Exports in Echo v5 (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Identifies middleware functions and types that were removed or consolidated in Echo v5. This includes logger and timeout functionalities, along with various default configuration structs. ```go // Removed in v5 func Logger() echo.MiddlewareFunc func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc func Timeout() echo.MiddlewareFunc func TimeoutWithConfig(config TimeoutConfig) echo.MiddlewareFunc type ErrKeyAuthMissing struct{ ... } type CSRFErrorHandler func(err error, c echo.Context) error type LoggerConfig struct{ ... } type LogErrorFunc func(c echo.Context, err error, stack []byte) error type TargetProvider interface{ ... } type TrailingSlashConfig struct{ ... } type TimeoutConfig struct{ ... } Also removed defaults: `DefaultBasicAuthConfig`, `DefaultBodyDumpConfig`, `DefaultBodyLimitConfig`, `DefaultCORSConfig`, `DefaultDecompressConfig`, `DefaultGzipConfig`, `DefaultLoggerConfig`, `DefaultRedirectConfig`, `DefaultRequestIDConfig`, `DefaultRewriteConfig`, `DefaultTimeoutConfig`, `DefaultTrailingSlashConfig`. ``` -------------------------------- ### Response Structure and Helper Updates Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Updates to the Response struct and helper functions. The Response now embeds http.ResponseWriter, and NewResponse accepts a slog.Logger. ```go func (c *Context) Response() http.ResponseWriter type Response struct { http.ResponseWriter Status int Size int64 Committed bool } func NewResponse(w http.ResponseWriter, logger *slog.Logger) *Response func UnwrapResponse(rw http.ResponseWriter) (*Response, error) ``` -------------------------------- ### Renderer Interface Changes Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Details the changes in the Renderer interface, including parameter reordering and type updates. ```APIDOC ## Renderer Interface ### v4 ```go type Renderer interface { Render(io.Writer, string, interface{}, Context) error } ``` ### v5 ```go type Renderer interface { Render(c *Context, w io.Writer, templateName string, data any) error } ``` **Description**: The `Renderer` interface has seen changes in parameter order and types. In v5, the `Context` parameter is now a pointer (`*Context`) and is placed first. The data parameter type has been updated from `interface{}` to `any`. ``` -------------------------------- ### Response Type Changed (v4 vs v5) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Illustrates the change in the Context.Response() method and the Response struct between Echo v4 and v5. ```APIDOC ## Response Type Changed ### v4 ```go func (c Context) Response() *Response type Response struct { Writer http.ResponseWriter Status int Size int64 Committed bool } func NewResponse(w http.ResponseWriter, e *Echo) *Response ``` ### v5 ```go func (c *Context) Response() http.ResponseWriter type Response struct { http.ResponseWriter // Embedded Status int Size int64 Committed bool } func NewResponse(w http.ResponseWriter, logger *slog.Logger) *Response func UnwrapResponse(rw http.ResponseWriter) (*Response, error) ``` **Changes:** - Context.Response() returns `http.ResponseWriter` instead of `*Response` - Response now embeds `http.ResponseWriter` - NewResponse takes `*slog.Logger` instead of `*Echo` - New `UnwrapResponse()` helper function ``` -------------------------------- ### JSONSerializer Interface Updates (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Compares the JSONSerializer interface definitions between Echo v4 and v5. Version 5 updates the context parameter type and the type for the data being serialized/deserialized. ```go // v4 type JSONSerializer interface { Serialize(c Context, i interface{}, indent string) error Deserialize(c Context, i interface{}) error } // v5 type JSONSerializer interface { Serialize(c *Context, target any, indent string) error Deserialize(c *Context, target any) error } ``` -------------------------------- ### Middleware Package Changes - Signature and Type Updates Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Details signature and type modifications in various middleware functions and types. ```APIDOC ## Middleware Package Changes ### Signature and Type Updates - **CORS**: Now accepts optional `allowOrigins`. ```go func CORS(allowOrigins ...string) echo.MiddlewareFunc ``` - **BodyLimit**: Accepts bytes as an integer. ```go func BodyLimit(limitBytes int64) echo.MiddlewareFunc ``` - **DefaultSkipper**: Now uses `*echo.Context`. ```go func DefaultSkipper(c *echo.Context) bool ``` - **Trailing Slash**: Config functions renamed and split. ```go func AddTrailingSlashWithConfig(config AddTrailingSlashConfig) echo.MiddlewareFunc func RemoveTrailingSlashWithConfig(config RemoveTrailingSlashConfig) echo.MiddlewareFunc type AddTrailingSlashConfig struct{ ... } type RemoveTrailingSlashConfig struct{ ... } ``` - **Auth / Extractor**: Signatures updated to use `*echo.Context` and include `ExtractorSource`. ```go type BasicAuthValidator func(c *echo.Context, user string, password string) (bool, error) type Extractor func(c *echo.Context) (string, error) type ExtractorSource string type KeyAuthValidator func(c *echo.Context, key string, source ExtractorSource) (bool, error) type KeyAuthErrorHandler func(c *echo.Context, err error) error ``` - **BodyDump**: Handler now includes an `err` parameter. ```go type BodyDumpHandler func(c *echo.Context, reqBody []byte, resBody []byte, err error) ``` - **ValuesExtractor**: Updated return values and `CreateExtractors` parameter. ```go type ValuesExtractor func(c *echo.Context) ([]string, ExtractorSource, error) func CreateExtractors(lookups string, limit uint) ([]ValuesExtractor, error) type ValueExtractorError struct{ ... } ``` - **New Constants**: `KB` constant added. ```go const KB = 1024 ``` - **Rate Limiter Store**: `NewRateLimiterMemoryStore` now takes `float64` for rate limit. ```go func NewRateLimiterMemoryStore(rateLimit float64) (store *RateLimiterMemoryStore) ``` ``` -------------------------------- ### HTTPError Simplified (v4 vs v5) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Details the changes to the HTTPError struct and its associated constructor and methods between Echo v4 and v5. ```APIDOC ## HTTPError Simplified ### v4 ```go type HTTPError struct { Internal error Message interface{} // Can be any type Code int } func NewHTTPError(code int, message ...interface{}) *HTTPError ``` ### v5 ```go type HTTPError struct { Code int Message string // Now string only // Has unexported fields (Internal moved) } func NewHTTPError(code int, message string) *HTTPError func (he HTTPError) Wrap(err error) error // New method func (he *HTTPError) StatusCode() int // Implements HTTPStatusCoder ``` **Changes:** - `Message` field changed from `interface{}` to `string` - `NewHTTPError()` now takes `string` instead of `...interface{}` - Added `HTTPStatusCoder` interface and `StatusCode()` method - Added `Wrap(err error)` method for error wrapping ``` -------------------------------- ### Logger Integration (slog) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Details the replacement of the custom Logger interface with the standard library's log/slog. ```APIDOC ## Logger Integration ### Description Echo v5 removes the custom Logger interface in favor of the standard library `log/slog` package. This provides better structured logging capabilities. ### Usage #### Accessing Logger ```go // In v5, the context provides access to the slog.Logger func MyHandler(c *echo.Context) error { c.Logger().Info("processing request") return nil } ``` ``` -------------------------------- ### Context Handler Signature Change (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Illustrates the change in the handler function signature for Echo's Context from an interface to a pointer to a concrete struct. This is a critical breaking change requiring all handler functions to be updated. ```go package main import ( "net/http" "github.com/labstack/echo/v4" ) // v4 (master) signature // func handler(c echo.Context) error { // return c.JSON(http.StatusOK, map[string]string{"hello": "world"}) // } // v5 signature func MyHandler(c *echo.Context) error { return c.JSON(http.StatusOK, map[string]string{"hello": "world"}) } ``` -------------------------------- ### Update Route Info Access Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Shows the change in accessing route information by moving from the Echo instance directly to the Router component. ```go routes := e.Router().Routes() for _, r := range routes { fmt.Println(r.Method, r.Path) } ``` -------------------------------- ### Update Form Parameter Function Names Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md The form parameter retrieval functions have been renamed from FormParam to FormValue in v5 to better reflect their purpose, and they now accept a pointer to the Context. ```go // v4 func FormParam[T any](c Context, key string, opts ...any) (T, error) func FormParamOr[T any](c Context, key string, defaultValue T, opts ...any) (T, error) // v5 func FormValue[T any](c *Context, key string, opts ...any) (T, error) func FormValueOr[T any](c *Context, key string, defaultValue T, opts ...any) (T, error) ``` -------------------------------- ### Middleware Package Changes - Removed/Consolidated Middleware Exports Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Highlights middleware exports that were removed or consolidated in v5. ```APIDOC ## Middleware Package Changes ### Removed/Consolidated Middleware Exports - **Removed in v5**: Logger and Timeout middleware functions and their `WithConfig` variants. ```go // Removed in v5 func Logger() echo.MiddlewareFunc func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc func Timeout() echo.MiddlewareFunc func TimeoutWithConfig(config TimeoutConfig) echo.MiddlewareFunc ``` - **Removed Types/Interfaces**: Several types and interfaces have been removed or consolidated. ```go type ErrKeyAuthMissing struct{ ... } type CSRFErrorHandler func(err error, c echo.Context) error type LoggerConfig struct{ ... } type LogErrorFunc func(c echo.Context, err error, stack []byte) error type TargetProvider interface{ ... } type TrailingSlashConfig struct{ ... } type TimeoutConfig struct{ ... } ``` - **Removed Defaults**: Default configuration structs for various middleware have been removed. ```go // Removed defaults: // DefaultBasicAuthConfig, DefaultBodyDumpConfig, DefaultBodyLimitConfig, // DefaultCORSConfig, DefaultDecompressConfig, DefaultGzipConfig, DefaultLoggerConfig, // DefaultRedirectConfig, DefaultRequestIDConfig, DefaultRewriteConfig, DefaultTimeoutConfig, // DefaultTrailingSlashConfig ``` ``` -------------------------------- ### NewBindingError Function Signature Changes (Go) Source: https://github.com/labstack/echo/blob/master/API_CHANGES_V5.md Shows the evolution of the NewBindingError function signature from Echo v4 to v5. The 'message' parameter type changed from interface{} to string, and 'internalError' to 'err'. ```go // v4 func NewBindingError(sourceParam string, values []string, message interface{}, internalError error) error // v5 func NewBindingError(sourceParam string, values []string, message string, err error) error ```