Golang API Gateway: Routing, Rate Limiting, JWT Auth Middleware E-Commerce
Implementing the Santekno Shop API Gateway with Echo middleware. Centralized routing, per-endpoint rate limiting, JWT auth, request ID, CORS, and structured logging for production.
Building an API Gateway with Golang and Echo middleware doesn’t always mean running a separate service. In Santekno Shop, the API Gateway is a middleware stack that runs in front of all handlers within a single process. In this article we complete its middleware chain: request ID, structured logging, per-endpoint rate limiting, JWT auth, CORS, and centralized error handling — everything a production-grade gateway needs without the overhead of a service mesh.
14.01 Middleware Stack Overview
Before writing each middleware one by one, we need to see the full ordering, because execution order determines correctness. The diagram below shows a request’s journey from client to response, passing through every middleware layer.
1Incoming request:
2 [Client]
3 ↓ HTTPS
4 [Recover Middleware] → panic recovery
5 ↓
6 [Request ID Middleware] → generate X-Request-ID
7 ↓
8 [Logger Middleware] → structured request log
9 ↓
10 [CORS Middleware] → cross-origin headers
11 ↓
12 [Rate Limit Middleware] → per-IP or per-endpoint limit
13 ↓
14 [JWT Auth Middleware] → validate Bearer token (protected routes only)
15 ↓
16 [Handler] → business logic
17 ↓
18 [Error Handler] → centralized error → HTTP response
19 ↓
20 [Response]Notice that Recover sits outermost so it can catch panics from all other middleware, and JWT is only active on protected routes. This is the ordering we’ll build step by step throughout the article.
14.02 Request ID Middleware
Every request needs a unique identity so it can be traced across logs and services. The middleware below honors the upstream X-Request-ID if present, or generates a new one, then stores it in the context and response header.
1// delivery/http/middleware/request_id.go
2
3package middleware
4
5import (
6 "github.com/google/uuid"
7 "github.com/labstack/echo/v4"
8)
9
10const RequestIDKey = "request_id"
11
12func RequestID() echo.MiddlewareFunc {
13 return func(next echo.HandlerFunc) echo.HandlerFunc {
14 return func(c echo.Context) error {
15 // Prioritize the incoming request ID (from the load balancer or upstream)
16 requestID := c.Request().Header.Get("X-Request-ID")
17 if requestID == "" {
18 requestID = uuid.New().String()
19 }
20
21 // Set it on the response header and context
22 c.Response().Header().Set("X-Request-ID", requestID)
23 c.Set(RequestIDKey, requestID)
24
25 return next(c)
26 }
27 }
28}
29
30func GetRequestID(c echo.Context) string {
31 if id, ok := c.Get(RequestIDKey).(string); ok {
32 return id
33 }
34 return "unknown"
35}By prioritizing the upstream header, the request ID set by the load balancer is preserved so tracing isn’t broken. This ID will appear in every log line and response, becoming the foundation of distributed tracing.
14.03 Structured Logger Middleware
Structured (JSON) logs are far easier to ingest into ELK or Loki than free-form text logs. The middleware below records every request with latency, status, path, and IP, and selects the log level based on the response status.
1// delivery/http/middleware/logger.go
2
3package middleware
4
5import (
6 "time"
7
8 "github.com/labstack/echo/v4"
9 "github.com/rs/zerolog"
10)
11
12func Logger(log zerolog.Logger) echo.MiddlewareFunc {
13 return func(next echo.HandlerFunc) echo.HandlerFunc {
14 return func(c echo.Context) error {
15 start := time.Now()
16
17 err := next(c)
18
19 status := c.Response().Status
20 latency := time.Since(start)
21
22 event := log.Info()
23 if err != nil || status >= 500 {
24 event = log.Error().Err(err)
25 } else if status >= 400 {
26 event = log.Warn()
27 }
28
29 event.
30 Str("request_id", GetRequestID(c)).
31 Str("method", c.Request().Method).
32 Str("path", c.Request().URL.Path).
33 Str("ip", c.RealIP()).
34 Int("status", status).
35 Dur("latency_ms", latency).
36 Str("user_agent", c.Request().UserAgent()).
37 Msg("request")
38
39 return err
40 }
41 }
42}Mapping status to log level (5xx → error, 4xx → warn, everything else → info) makes alerting easy: just watch the volume of error-level logs. Because the logger reads GetRequestID, it must be installed after the RequestID middleware.
14.04 Rate Limiter: Per Endpoint Strategy
Not all endpoints deserve the same limit — login must be far stricter than browsing products. The middleware below sets different limits per endpoint and rejects requests exceeding the quota with a 429 status.
1// delivery/http/middleware/rate_limit.go
2
3package middleware
4
5import (
6 "fmt"
7 "net/http"
8 "time"
9
10 "github.com/labstack/echo/v4"
11 redisinfra "github.com/santekno/santekno-shop/internal/infrastructure/redis"
12 "github.com/santekno/santekno-shop/pkg/apierror"
13)
14
15type RateLimitConfig struct {
16 MaxRequests int
17 Window time.Duration
18 KeyPrefix string // to distinguish the limit per endpoint
19}
20
21var EndpointLimits = map[string]RateLimitConfig{
22 // Auth endpoints — strictest
23 "/api/v1/auth/login": {MaxRequests: 5, Window: 15 * time.Minute, KeyPrefix: "login"},
24 "/api/v1/auth/register": {MaxRequests: 10, Window: time.Hour, KeyPrefix: "register"},
25
26 // Order endpoint — medium
27 "/api/v1/orders": {MaxRequests: 20, Window: time.Minute, KeyPrefix: "place_order"},
28
29 // Webhook — only from the payment gateway (can whitelist the IP)
30 "/api/v1/webhooks/payment": {MaxRequests: 100, Window: time.Minute, KeyPrefix: "webhook"},
31
32 // Default: all other endpoints
33 "default": {MaxRequests: 200, Window: time.Minute, KeyPrefix: "api"},
34}
35
36func RateLimit(limiter *redisinfra.RateLimiter) echo.MiddlewareFunc {
37 return func(next echo.HandlerFunc) echo.HandlerFunc {
38 return func(c echo.Context) error {
39 cfg, ok := EndpointLimits[c.Path()]
40 if !ok {
41 cfg = EndpointLimits["default"]
42 }
43
44 ip := c.RealIP()
45 key := fmt.Sprintf("ratelimit:%s:%s", cfg.KeyPrefix, ip)
46 windowSecs := int(cfg.Window.Seconds())
47
48 allowed, err := limiter.Allow(c.Request().Context(), key, cfg.MaxRequests, windowSecs)
49 if err != nil {
50 // Redis error → allow (degrade gracefully)
51 return next(c)
52 }
53
54 if !allowed {
55 c.Response().Header().Set("Retry-After", fmt.Sprintf("%d", windowSecs))
56 return c.JSON(http.StatusTooManyRequests,
57 apierror.Response{Error: "TOO_MANY_REQUESTS"})
58 }
59
60 return next(c)
61 }
62 }
63}This per-endpoint strategy maps directly onto the acceptance criteria in the spec — for example login 5 times per 15 minutes per IP. Note the graceful degradation too: if Redis errors, the request is allowed through rather than wrongly blocking the user.
14.05 CORS Middleware
A frontend on a different origin needs correct CORS headers, especially when sending Authorization and Idempotency-Key. The configuration below sets the allowed origins, methods, and headers exposed to the browser.
1// delivery/http/middleware/cors.go
2
3package middleware
4
5import (
6 echomiddleware "github.com/labstack/echo/v4/middleware"
7 "github.com/labstack/echo/v4"
8)
9
10func CORS(allowedOrigins []string) echo.MiddlewareFunc {
11 return echomiddleware.CORSWithConfig(echomiddleware.CORSConfig{
12 AllowOrigins: allowedOrigins,
13 // Development: ["*"]
14 // Production: ["https://santekno.com", "https://app.santekno.com"]
15
16 AllowMethods: []string{
17 "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS",
18 },
19 AllowHeaders: []string{
20 "Authorization",
21 "Content-Type",
22 "X-Request-ID",
23 "Idempotency-Key",
24 },
25 ExposeHeaders: []string{
26 "X-Request-ID",
27 "X-RateLimit-Limit",
28 "X-RateLimit-Remaining",
29 "Retry-After",
30 },
31 MaxAge: 3600, // preflight cache 1 hour
32 })
33}Placing Idempotency-Key and X-Request-ID in the allowed/exposed headers is important so the idempotency and tracing features we’ve built are actually usable from the browser. A MaxAge of 1 hour reduces the number of preflight requests.
14.06 JWT Middleware: Full Implementation
Protected routes need Bearer token validation and injection of claims into the context. The code below implements a mandatory JWT, an optional variant for semi-public endpoints, and a helper to fetch the user ID.
1// delivery/http/middleware/auth.go
2
3package middleware
4
5import (
6 "net/http"
7 "strings"
8
9 "github.com/google/uuid"
10 "github.com/labstack/echo/v4"
11 "github.com/santekno/santekno-shop/pkg/apierror"
12 "github.com/santekno/santekno-shop/pkg/token"
13)
14
15const (
16 UserIDKey = "user_id"
17 UserEmailKey = "user_email"
18)
19
20// JWT: validate the Bearer token and inject claims into the context
21func JWT(tokenSvc *token.JWTService) echo.MiddlewareFunc {
22 return func(next echo.HandlerFunc) echo.HandlerFunc {
23 return func(c echo.Context) error {
24 authHeader := c.Request().Header.Get("Authorization")
25 if !strings.HasPrefix(authHeader, "Bearer ") {
26 return c.JSON(http.StatusUnauthorized,
27 apierror.Response{Error: "UNAUTHORIZED"})
28 }
29
30 tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
31 claims, err := tokenSvc.ValidateAccess(tokenStr)
32 if err != nil {
33 return c.JSON(http.StatusUnauthorized,
34 apierror.Response{Error: "UNAUTHORIZED"})
35 }
36
37 c.Set(UserIDKey, claims.UserID)
38 c.Set(UserEmailKey, claims.Email)
39 return next(c)
40 }
41 }
42}
43
44// OptionalJWT: does not require auth but parses it if present
45// Useful for endpoints accessible either authenticated or anonymously
46func OptionalJWT(tokenSvc *token.JWTService) echo.MiddlewareFunc {
47 return func(next echo.HandlerFunc) echo.HandlerFunc {
48 return func(c echo.Context) error {
49 authHeader := c.Request().Header.Get("Authorization")
50 if strings.HasPrefix(authHeader, "Bearer ") {
51 tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
52 if claims, err := tokenSvc.ValidateAccess(tokenStr); err == nil {
53 c.Set(UserIDKey, claims.UserID)
54 c.Set(UserEmailKey, claims.Email)
55 }
56 }
57 return next(c)
58 }
59 }
60}
61
62func GetUserID(c echo.Context) (uuid.UUID, bool) {
63 uid, ok := c.Get(UserIDKey).(uuid.UUID)
64 return uid, ok
65}These two variants cover two different needs: JWT rejects requests without a valid token, while OptionalJWT still lets anonymous requests through but recognizes the user if a token is present. The handler simply calls GetUserID to obtain the user identity in a type-safe way.
14.07 Webhook Signature Middleware
Webhooks from the payment gateway don’t use JWT — their authenticity is verified via an HMAC signature. The middleware below reads the body, computes an HMAC-SHA256, and compares it against the sent signature, without destroying the body for the handler.
1// delivery/http/middleware/webhook_auth.go
2
3package middleware
4
5import (
6 "bytes"
7 "crypto/hmac"
8 "crypto/sha256"
9 "encoding/hex"
10 "io"
11 "net/http"
12
13 "github.com/labstack/echo/v4"
14 "github.com/santekno/santekno-shop/pkg/apierror"
15)
16
17// WebhookAuth: verify the HMAC-SHA256 signature for webhook endpoints
18func WebhookAuth(secret string) echo.MiddlewareFunc {
19 return func(next echo.HandlerFunc) echo.HandlerFunc {
20 return func(c echo.Context) error {
21 signature := c.Request().Header.Get("X-Signature")
22 if signature == "" {
23 // Check body.signature as a fallback (Article 09 uses the body)
24 return next(c)
25 }
26
27 // Read the body (without consuming it)
28 body, err := io.ReadAll(c.Request().Body)
29 if err != nil {
30 return c.JSON(http.StatusBadRequest,
31 apierror.Response{Error: "INVALID_REQUEST"})
32 }
33 // Restore the body for the handler
34 c.Request().Body = io.NopCloser(bytes.NewReader(body))
35
36 // Verify signature
37 mac := hmac.New(sha256.New, []byte(secret))
38 mac.Write(body)
39 expected := hex.EncodeToString(mac.Sum(nil))
40
41 if !hmac.Equal([]byte(expected), []byte(signature)) {
42 return c.JSON(http.StatusUnauthorized,
43 apierror.Response{Error: "INVALID_SIGNATURE"})
44 }
45
46 return next(c)
47 }
48 }
49}The technical key is io.NopCloser(bytes.NewReader(body)), which restores the body after reading, so the handler can still parse the payload. Using hmac.Equal (not ==) is also important to prevent a timing attack.
14.08 Panic Recovery Middleware
A single unhandled panic can bring down the entire server. The middleware below installs a recover() that catches the panic, logs the stack trace, and returns a 500 instead of letting the process die.
1// delivery/http/middleware/recover.go
2
3package middleware
4
5import (
6 "fmt"
7 "net/http"
8 "runtime/debug"
9
10 "github.com/labstack/echo/v4"
11 "github.com/rs/zerolog"
12 "github.com/santekno/santekno-shop/pkg/apierror"
13)
14
15func Recover(log zerolog.Logger) echo.MiddlewareFunc {
16 return func(next echo.HandlerFunc) echo.HandlerFunc {
17 return func(c echo.Context) (err error) {
18 defer func() {
19 if r := recover(); r != nil {
20 log.Error().
21 Str("request_id", GetRequestID(c)).
22 Str("panic", fmt.Sprintf("%v", r)).
23 Str("stack", string(debug.Stack())).
24 Msg("panic recovered")
25
26 err = c.JSON(http.StatusInternalServerError,
27 apierror.Response{Error: "INTERNAL_ERROR"})
28 }
29 }()
30 return next(c)
31 }
32 }
33}Because the stack trace is logged too, developers still get a signal to fix the bug even though that request failed. This is why Recover must be the outermost middleware — it needs to wrap all other middleware so a panic anywhere is caught.
14.09 Router: Full Setup
All middleware and routes must be assembled in one place in the correct order. The code below composes global middleware, health checks, public routes, the protected group with JWT, and webhooks in a single SetupRouter function.
1// delivery/http/router.go
2
3package http
4
5import (
6 "github.com/labstack/echo/v4"
7 "github.com/santekno/santekno-shop/config"
8 "github.com/santekno/santekno-shop/delivery/http/handler"
9 "github.com/santekno/santekno-shop/delivery/http/middleware"
10 "github.com/santekno/santekno-shop/pkg/token"
11 redisinfra "github.com/santekno/santekno-shop/internal/infrastructure/redis"
12 "github.com/rs/zerolog"
13)
14
15func SetupRouter(
16 c *Container,
17 cfg *config.Config,
18 log zerolog.Logger,
19 tokenSvc *token.JWTService,
20 rateLimiter *redisinfra.RateLimiter,
21) *echo.Echo {
22 e := echo.New()
23 e.HideBanner = true
24
25 // Validator
26 e.Validator = NewValidator()
27
28 // ────────────────────────────────────────────────
29 // GLOBAL MIDDLEWARE (all requests)
30 // ────────────────────────────────────────────────
31 e.Use(middleware.Recover(log))
32 e.Use(middleware.RequestID())
33 e.Use(middleware.Logger(log))
34 e.Use(middleware.CORS(cfg.App.AllowedOrigins))
35 e.Use(middleware.Gzip())
36 e.Use(middleware.RateLimit(rateLimiter))
37
38 // ────────────────────────────────────────────────
39 // HEALTH CHECK (no auth, no rate limit override)
40 // ────────────────────────────────────────────────
41 e.GET("/health", c.HealthHandler.Handle)
42 e.GET("/ready", c.HealthHandler.Ready)
43
44 // ────────────────────────────────────────────────
45 // API V1
46 // ────────────────────────────────────────────────
47 api := e.Group("/api/v1")
48
49 // Public routes (no JWT)
50 auth := api.Group("/auth")
51 auth.POST("/register", c.AuthHandler.Register)
52 auth.POST("/login", c.AuthHandler.Login)
53 auth.POST("/refresh", c.AuthHandler.RefreshToken)
54 auth.POST("/logout", c.AuthHandler.Logout)
55
56 // Products: public read, no auth
57 products := api.Group("/products")
58 products.GET("", c.ProductHandler.List)
59 products.GET("/:id", c.ProductHandler.Get)
60
61 // Protected routes (require JWT)
62 protected := api.Group("")
63 protected.Use(middleware.JWT(tokenSvc))
64
65 // Orders
66 protected.POST("/orders", c.OrderHandler.PlaceOrder)
67 protected.GET("/orders", c.OrderHandler.GetOrders)
68 protected.GET("/orders/:id", c.OrderHandler.GetOrder)
69 protected.DELETE("/orders/:id", c.OrderHandler.CancelOrder)
70
71 // Profile
72 protected.GET("/me", c.UserHandler.GetProfile)
73
74 // Webhooks (signature verification, not JWT)
75 webhooks := api.Group("/webhooks")
76 webhooks.POST("/payment", c.WebhookHandler.HandlePayment)
77
78 // ────────────────────────────────────────────────
79 // CENTRALIZED ERROR HANDLER
80 // ────────────────────────────────────────────────
81 e.HTTPErrorHandler = CustomErrorHandler(log)
82
83 return e
84}Notice the route group split: public (auth, product read), protected (JWT via protected.Use), and webhook (signature in the handler). This structure makes the security policy readable from the router alone — no need to trace through each handler.
14.10 Custom Error Handler
Errors from various sources must be normalized into a single JSON format. The code below replaces Echo’s default error handler, maps HTTPError to a consistent response, and logs unexpected errors.
1// delivery/http/error_handler.go
2
3package http
4
5import (
6 "net/http"
7
8 "github.com/labstack/echo/v4"
9 "github.com/rs/zerolog"
10 "github.com/santekno/santekno-shop/pkg/apierror"
11)
12
13func CustomErrorHandler(log zerolog.Logger) echo.HTTPErrorHandler {
14 return func(err error, c echo.Context) {
15 if c.Response().Committed {
16 return
17 }
18
19 code := http.StatusInternalServerError
20 var response apierror.Response
21
22 switch e := err.(type) {
23 case *echo.HTTPError:
24 code = e.Code
25 switch code {
26 case http.StatusNotFound:
27 response = apierror.Response{Error: "NOT_FOUND"}
28 case http.StatusMethodNotAllowed:
29 response = apierror.Response{Error: "METHOD_NOT_ALLOWED"}
30 default:
31 response = apierror.Response{Error: "HTTP_ERROR", Detail: fmt.Sprint(e.Message)}
32 }
33 default:
34 log.Error().
35 Str("request_id", middleware.GetRequestID(c)).
36 Err(err).
37 Msg("unhandled error")
38 response = apierror.Response{Error: "INTERNAL_ERROR"}
39 }
40
41 c.JSON(code, response)
42 }
43}With this centralized handler, every error path — from a 404 router miss to an unexpected panic — produces a uniform JSON shape for the client. Unexpected errors are still logged in full with the request ID for investigation.
14.11 Rate Limit Response Headers
A well-behaved client wants to know how much request quota it has left before hitting a 429. The middleware below adds X-RateLimit-* headers so clients can pace themselves and show an informative UI.
1// Add rate limit info to the response headers
2// So the client knows how many requests remain available
3
4func RateLimitWithHeaders(limiter *redisinfra.RateLimiter) echo.MiddlewareFunc {
5 return func(next echo.HandlerFunc) echo.HandlerFunc {
6 return func(c echo.Context) error {
7 cfg, ok := EndpointLimits[c.Path()]
8 if !ok { cfg = EndpointLimits["default"] }
9
10 ip := c.RealIP()
11 key := fmt.Sprintf("ratelimit:%s:%s", cfg.KeyPrefix, ip)
12
13 count, _ := limiter.GetCount(c.Request().Context(), key)
14 remaining := cfg.MaxRequests - int(count)
15 if remaining < 0 { remaining = 0 }
16
17 c.Response().Header().Set("X-RateLimit-Limit",
18 fmt.Sprintf("%d", cfg.MaxRequests))
19 c.Response().Header().Set("X-RateLimit-Remaining",
20 fmt.Sprintf("%d", remaining))
21 c.Response().Header().Set("X-RateLimit-Window",
22 fmt.Sprintf("%d", int(cfg.Window.Seconds())))
23
24 allowed, _ := limiter.Allow(c.Request().Context(), key, cfg.MaxRequests, int(cfg.Window.Seconds()))
25 if !allowed {
26 c.Response().Header().Set("Retry-After", fmt.Sprintf("%d", int(cfg.Window.Seconds())))
27 return c.JSON(429, apierror.Response{Error: "TOO_MANY_REQUESTS"})
28 }
29
30 return next(c)
31 }
32 }
33}Headers like X-RateLimit-Remaining and Retry-After let the client apply polite backoff instead of hammering the server repeatedly. This is a variant of the basic rate limiter that trades a little overhead for a much better client experience.
14.12 Request Timeout Middleware
A slow query can hold a goroutine hostage and exhaust server resources. The middleware below installs a per-request context timeout and returns a 504 if the handler exceeds the deadline.
1// delivery/http/middleware/timeout.go
2
3package middleware
4
5import (
6 "context"
7 "net/http"
8 "time"
9
10 "github.com/labstack/echo/v4"
11 "github.com/santekno/santekno-shop/pkg/apierror"
12)
13
14// Timeout: cancel the request context after a certain duration
15func Timeout(d time.Duration) echo.MiddlewareFunc {
16 return func(next echo.HandlerFunc) echo.HandlerFunc {
17 return func(c echo.Context) error {
18 ctx, cancel := context.WithTimeout(c.Request().Context(), d)
19 defer cancel()
20
21 // Replace request context
22 c.SetRequest(c.Request().WithContext(ctx))
23
24 done := make(chan error, 1)
25 go func() { done <- next(c) }()
26
27 select {
28 case err := <-done:
29 return err
30 case <-ctx.Done():
31 return c.JSON(http.StatusGatewayTimeout,
32 apierror.Response{Error: "REQUEST_TIMEOUT"})
33 }
34 }
35 }
36}
37
38// Per-endpoint timeout configuration:
39// webhook endpoint: 10 seconds (from spec)
40// standard endpoints: 30 secondsBecause the context is propagated to the handler and DB query, this timeout truly cancels the upstream work, not just returns a fast response. The timeout value should be per-endpoint — webhook 10 seconds per the spec, ordinary endpoints 30 seconds.
14.13 API Versioning Strategy
Sooner or later, the API will have a breaking change and need a new version without breaking old clients. The code below shows a per-version group structure and a deprecation header to guide clients migrating from v1 to v2.
1// Router setup supporting multiple API versions
2
3api := e.Group("/api")
4
5// V1 (current)
6v1 := api.Group("/v1")
7v1.GET("/products", c.ProductHandler.List)
8// ...
9
10// V2 (future — when there's a breaking change)
11// v2 := api.Group("/v2")
12// v2.GET("/products", c.ProductHandlerV2.List) // different response format
13
14// Deprecated header for v1 once v2 exists:
15func DeprecationHeader(version, sunsetDate string) echo.MiddlewareFunc {
16 return func(next echo.HandlerFunc) echo.HandlerFunc {
17 return func(c echo.Context) error {
18 c.Response().Header().Set("Deprecation", "true")
19 c.Response().Header().Set("Sunset", sunsetDate)
20 c.Response().Header().Set("Link",
21 `<https://docs.santekno.com/api/v2>; rel="successor-version"`)
22 return next(c)
23 }
24 }
25}The Deprecation, Sunset, and Link headers are the standard way to tell clients that v1 will be discontinued and where to migrate. Setting up the version structure early is far cheaper than reworking routing when v2 becomes urgent.
14.14 IP Whitelist for the Webhook
As an extra defense layer, the payment webhook should only accept requests from known gateway IPs. The middleware below parses a list of CIDRs and rejects IPs not in the whitelist.
1// delivery/http/middleware/ip_whitelist.go
2
3package middleware
4
5import (
6 "net"
7 "net/http"
8
9 "github.com/labstack/echo/v4"
10)
11
12// IPWhitelist: only allow certain IPs for the webhook
13// Use together with WebhookAuth as defense-in-depth
14func IPWhitelist(allowedCIDRs []string) echo.MiddlewareFunc {
15 var networks []*net.IPNet
16 for _, cidr := range allowedCIDRs {
17 _, network, err := net.ParseCIDR(cidr)
18 if err == nil {
19 networks = append(networks, network)
20 }
21 }
22
23 return func(next echo.HandlerFunc) echo.HandlerFunc {
24 return func(c echo.Context) error {
25 ip := net.ParseIP(c.RealIP())
26
27 for _, network := range networks {
28 if network.Contains(ip) {
29 return next(c)
30 }
31 }
32
33 // IP not in the whitelist
34 return c.JSON(http.StatusForbidden,
35 map[string]string{"error": "FORBIDDEN"})
36 }
37 }
38}
39
40// Usage:
41// webhooks.Use(middleware.IPWhitelist(cfg.Payment.AllowedIPs))
42// cfg.Payment.AllowedIPs = ["203.0.113.0/24", "198.51.100.0/24"]Combined with the HMAC signature, the IP whitelist forms defense-in-depth: the IP whitelist filters coarsely (blocking scanners), the signature verifies payload integrity. The CIDRs are parsed once at startup so the per-request check stays fast.
14.15 Middleware Test
Critical middleware like the rate limiter must have tests that ensure it behaves correctly. The test below uses gomock to simulate the limit being exceeded and verifies the 429 response with the correct body.
1// delivery/http/middleware/rate_limit_test.go
2
3func TestRateLimit_ExceedsLimit_Returns429(t *testing.T) {
4 e := echo.New()
5 ctrl := gomock.NewController(t)
6 defer ctrl.Finish()
7
8 mockLimiter := mock.NewMockRateLimiter(ctrl)
9
10 // Simulate rate limit exceeded
11 mockLimiter.EXPECT().
12 Allow(gomock.Any(), gomock.Any(), 5, 900).
13 Return(false, nil)
14
15 mw := middleware.RateLimit(mockLimiter)
16 handler := mw(func(c echo.Context) error {
17 return c.JSON(http.StatusOK, "ok")
18 })
19
20 req := httptest.NewRequest("POST", "/api/v1/auth/login", nil)
21 rec := httptest.NewRecorder()
22 c := e.NewContext(req, rec)
23 c.SetPath("/api/v1/auth/login")
24
25 err := handler(c)
26 assert.NoError(t, err)
27 assert.Equal(t, http.StatusTooManyRequests, rec.Code)
28
29 var resp map[string]string
30 json.NewDecoder(rec.Body).Decode(&resp)
31 assert.Equal(t, "TOO_MANY_REQUESTS", resp["error"])
32}By setting the mock Allow to return false, the test verifies that the middleware produces a 429 and a TOO_MANY_REQUESTS body without calling the handler. This httptest + gomock pattern is reusable for testing other middleware.
14.16 Security Headers
Several common attacks can be mitigated just by adding HTTP security headers. The middleware below sets headers like HSTS, CSP, and X-Frame-Options on every response.
1// delivery/http/middleware/security.go
2
3package middleware
4
5import "github.com/labstack/echo/v4"
6
7// SecurityHeaders: add security-related HTTP headers
8func SecurityHeaders() echo.MiddlewareFunc {
9 return func(next echo.HandlerFunc) echo.HandlerFunc {
10 return func(c echo.Context) error {
11 h := c.Response().Header()
12 h.Set("X-Content-Type-Options", "nosniff")
13 h.Set("X-Frame-Options", "DENY")
14 h.Set("X-XSS-Protection", "1; mode=block")
15 h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
16 h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
17 h.Set("Content-Security-Policy",
18 "default-src 'self'; script-src 'self'; style-src 'self'")
19 return next(c)
20 }
21 }
22}These headers are cheap to set but close off a class of attacks like clickjacking (X-Frame-Options) and MIME sniffing (X-Content-Type-Options). HSTS forces the browser to always use HTTPS for your domain.
14.17 Readiness vs Liveness Probe
Kubernetes distinguishes “is the server alive” from “is the server ready to accept traffic” — and both need different endpoints. The code below separates liveness (/health), which is always 200, from readiness (/ready), which checks dependencies like the DB and Redis.
1// delivery/http/handler/health_handler.go
2
3// Liveness: is the server still running? (restart if it fails)
4func (h *HealthHandler) Handle(c echo.Context) error {
5 return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
6}
7
8// Readiness: is the server ready to take traffic? (remove from LB if it fails)
9func (h *HealthHandler) Ready(c echo.Context) error {
10 ctx, cancel := context.WithTimeout(c.Request().Context(), 3*time.Second)
11 defer cancel()
12
13 if err := h.db.Ping(ctx); err != nil {
14 return c.JSON(http.StatusServiceUnavailable, map[string]interface{}{
15 "status": "not_ready",
16 "reason": "database_unavailable",
17 })
18 }
19
20 if err := h.rdb.Ping(ctx).Err(); err != nil {
21 // Redis down is not a reason to stop traffic — degraded but still ready
22 return c.JSON(http.StatusOK, map[string]interface{}{
23 "status": "degraded",
24 "reasons": []string{"redis_unavailable"},
25 })
26 }
27
28 return c.JSON(http.StatusOK, map[string]string{"status": "ready"})
29}Notice the important decision: a DB down makes readiness return 503 (stop traffic), but a Redis down is only “degraded” and still returns 200 — consistent with the circuit breaker we built in the Redis article. This prevents Kubernetes from pulling the pod out of the load balancer just because the cache is having trouble.
14.18 Load Testing the Middleware Chain
A thick middleware stack can potentially add latency, so it needs to be verified with a load test. The k6 script below fires at the products endpoint with 100 virtual users and checks the status, request ID, and p95 latency.
1// k6 load test to verify the middleware doesn't add overhead
2// scripts/k6/middleware_test.js
3
4import http from 'k6/http';
5import { check } from 'k6';
6
7export let options = {
8 vus: 100, // 100 virtual users
9 duration: '30s', // 30 seconds
10};
11
12export default function () {
13 // Test: GET /products (public, no auth, has rate limit)
14 let res = http.get('http://localhost:8080/api/v1/products');
15 check(res, {
16 'status 200': (r) => r.status === 200,
17 'has request-id': (r) => r.headers['X-Request-Id'] !== undefined,
18 'p95 < 100ms': (r) => r.timings.duration < 100,
19 });
20}
21
22// Run: k6 run scripts/k6/middleware_test.js
23// Expected: 0% error rate, p95 < 100ms
The p95-under-100ms target ensures the entire middleware chain adds only negligible overhead. A load test like this should be part of CI so performance regressions are caught before production.
14.19 Middleware Execution Order
The middleware order isn’t a style preference — the wrong order can let a panic slip through or make CORS fail. The summary below explains the reasoning behind the correct order along with examples of what breaks if the order is wrong.
1Middleware execution order MATTERS:
2
31. Recover → must be first, catch panics from all other middleware
42. RequestID → generate the ID before logging
53. Logger → log after RequestID is available
64. CORS → preflight must be answered before the auth check
75. Gzip → compress before the rate limit check
86. RateLimit → check before reaching auth/handler
97. JWT Auth → only on the protected group
10
11ERROR: If Logger comes before Recover → a panic in Logger is not caught
12ERROR: If Auth comes before CORS → preflight (OPTIONS) hits the auth check → CORS fails
13ERROR: If RateLimit comes after JWT → auth overhead before the rate checkThe three error examples below are real mistakes that happen often — especially Auth before CORS, which makes preflight OPTIONS get rejected. Use this order as a checklist when adding new middleware.
14.20 Summary: API Gateway Complete
The Santekno Shop middleware stack is now production-ready and handles all cross-cutting concerns in a single process:
Request ID: every request has a unique ID for tracing, set from upstream or newly generated.
Structured Logging: JSON log per request with latency, status, path, IP — ready to ingest into ELK/Loki.
Rate Limiting: per-endpoint strategy — login stricter than product browse.
JWT Auth: Bearer token validation, claims injected into the context.
CORS: configured for allowed origins, exposed headers including X-Request-ID.
Error Handler: centralized — every error path gives a consistent JSON response.
Security Headers: HSTS, CSP, X-Frame-Options, XSS protection.
Readiness vs Liveness: Kubernetes-ready health endpoints.
Without a service mesh, Echo middleware already handles all the gateway needs at this scale. Once the application has a mature gateway, the next step is to wrap it in a container and deploy it from local to staging.