Extending Echo's context with custom functionality
// CustomContext wraps Echo's context with additional functionality
type CustomContext struct {
echo.Context
}
// Success sends a JSON success response
func (c *CustomContext) Success(data interface{}) error {
return c.JSON(http.StatusOK, map[string]interface{}{
"success": true,
"data": data,
"meta": map[string]interface{}{
"timestamp": time.Now().UTC(),
"requestId": c.Request().Header.Get("X-Request-ID"),
},
})
}
// Error sends a JSON error response
func (c *CustomContext) Error(status int, message string) error {
return c.JSON(status, map[string]interface{}{
"success": false,
"error": message,
"meta": map[string]interface{}{
"timestamp": time.Now().UTC(),
"requestId": c.Request().Header.Get("X-Request-ID"),
},
})
}
// GetUserAgent returns the request's User-Agent header
func (c *CustomContext) GetUserAgent() string {
return c.Request().UserAgent()
}
// CustomContextMiddleware creates a middleware that replaces the context
func CustomContextMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cc := &CustomContext{c}
return next(cc)
}
}
package main
import (
"net/http"
"time"
"github.com/labstack/echo/v4"
)
func main() {
e := echo.New()
// Register the custom context middleware
e.Use(CustomContextMiddleware)
// Standard Echo context route
e.GET("/standard", func(c echo.Context) error {
return c.String(http.StatusOK, "Standard Echo context response")
})
// Custom context route (will be wrapped by our middleware)
e.GET("/custom", func(c echo.Context) error {
// Type assertion to our CustomContext
cc := c.(*CustomContext)
// Use our custom methods
if cc.GetUserAgent() == "" {
return cc.Error(http.StatusBadRequest, "User-Agent header is required")
}
return cc.Success(map[string]interface{}{
"message": "Hello from Custom Context!",
"userAgent": cc.GetUserAgent(),
"features": []string{"Success()", "Error()", "GetUserAgent()"},
})
})
e.Logger.Fatal(e.Start(":1323"))
}
Add your own methods to Echo's context for cleaner code.
Type assertions ensure you're working with your custom context.
Seamlessly integrate with Echo's middleware system.
Made with DeepSite - 🧬 Remix