What Architec patter is better for make a gateway in go and why
- User
What Architec patter is better for make a gateway in go and why
- Assistant
First, what kind of “gateway” are we talking about?
Most teams use the word “gateway” to describe one of these two things:
Gateway Type Main Job Typical Traffic Good Examples Edge / API Gateway Expose a single public entry-point in front of many micro-services (REST, gRPC, GraphQL, etc.). Adds auth, rate-limit, logging, … HTTP/1.1, HTTP/2, gRPC, WebSockets Kong, Zuul, Traefik Service-to-service Reverse Proxy Internal hop that hides service discovery, retries, circuit breaking, etc. from callers Mostly gRPC or REST inside the cluster Linkerd, Istio sidecar Whichever flavor you need, the code-level architecture in Go ends up looking similar, so I’ll focus on patterns you can apply in Go code.
TL;DR – The sweet spot in Go
Reverse-Proxy + Chain-of-Responsibility (middleware) structured with Hexagonal/Clean Architecture is the winning combo for 90 % of Go-based gateways.
- Reverse-Proxy pattern
• Delegates the actual request to an upstream.
• In Go it’s literallyhttputil.ReverseProxy. - Chain-of-Responsibility (a.k.a. middleware pipeline)
• Each concern (auth, tracing, rate-limit, …) is a pluggable link in the chain.
• Perfectly maps tohttp.Handler→next http.Handler. - Hexagonal / Clean Architecture around it
• Keeps gateway-specific “delivery code” (HTTP) at the edge.
• Business logic (routing rules, auth policy, …) lives behind ports/interfaces, so you can unit-test it without HTTP.
Below is the why and a minimal working example.
Why this combo works so well in Go
Aspect Why the pattern shines Simplicity net/httpis in the std-lib, no extra heavy framework.Performance Go’s goroutines + zero-GC object reuse in ReverseProxy= low latency, high throughput.Extensibility New feature? Drop another middleware in the chain. Testability Core policy logic is decoupled behind ports: test with pure Go, no HTTP server needed. Operational maturity Same model powers popular OSS projects (Traefik, Caddy, Go-Proxy). You inherit best practices.
Code Sketch (≈40 lines)
package main import ( "log" "net/http" "net/http/httputil" "net/url" ) // --- Ports --- type Authorizer interface { Authorize(r *http.Request) error } // --- Adapters --- // Simple header-based authorizer example type HeaderAuthorizer struct{} func (h HeaderAuthorizer) Authorize(r *http.Request) error { if r.Header.Get("X-API-Key") == "secret" { return nil } return http.ErrNoCookie // use any error you like } // Middleware link func authMiddleware(a Authorizer, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if err := a.Authorize(r); err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) } func main() { // Upstream target target, _ := url.Parse("http://backend:8080") proxy := httputil.NewSingleHostReverseProxy(target) // Compose chain authorizer := HeaderAuthorizer{} handler := authMiddleware(authorizer, proxy) log.Println("gateway listening on :8080") log.Fatal(http.ListenAndServe(":8080", handler)) }Add logging, metrics, rate-limiting, circuit breaking, etc. the same way—just insert more middleware links.
Where other patterns fit in
Pattern / Approach When it can be better BFF (Backend-for-Frontend) If each UI (mobile, web) needs its own tailored gateway, BFF keeps code bases small & focused. Often still uses reverse-proxy + middleware under the hood, but separated per client. GraphQL Gateway When many services expose GraphQL ‑> you stitch schemas. Use graph-gophers/graphql-goplus middlewares.gRPC-Gateway If clients speak REST but services are gRPC, grpc-gatewayauto-generates the REST reverse-proxy layer.Envoy / Istio (Sidecar pattern) You don’t write Go. You configure. Great in k8s if you want out-of-the-box xDS, mTLS, retries, traffic splitting. Event-Driven / Broker Gateway For async workloads (MQTT, NATS, Kafka). Not typical for plain API gateway, but Go has first-class libs.
Decision Checklist
-
Do you need ultra-low level control and write code?
➜ Use Go Reverse-Proxy + Middleware. -
Is your team small and wants “zero-ops”?
➜ Prefer an off-the-shelf product (Traefik, Kong) and extend with plugins. -
Heavy gRPC shop?
➜grpc-gatewaypattern or embed Envoy. -
Need per-device custom endpoints (e.g., native mobile vs PWA)?
➜ BFF pattern (still in Go, but repo per client).
Final recommendation
Start with the idiomatic Go stack:
net/http + httputil.ReverseProxy ↳ chi / gorilla / std-lib Mux (router) ↳ middleware chain: auth, logging, metrics ↳ business logic behind interfaces → Hexagonal structureYou’ll get production-grade performance in a weekend and can evolve toward more sophisticated setups (Envoy, service mesh) later without throwing code away.
Feel free to drop more details about your use-case (traffic volume, protocols, auth style) and I can tailor the design further!
- Reverse-Proxy pattern
- User
Decide into layer and hexagonal
- Assistant
Below is a side-by-side cheat-sheet that should make the choice crystal-clear for a Go-based gateway.
(If you only have 2-3 handlers and no future growth expected → layered is “good enough”. Anything larger or long-lived → go Hexagonal / Clean.)
Glossary
• “Layered” = classic 3- or 4-tier (handler → service → repo → db)
• “Hexagonal / Clean” = Ports & Adapters, Use-Cases in the middle- Quick Comparison
Dimension Layered (N-tier) Hexagonal / Clean Core idea Stack of layers, outer calls inner Invert dependencies: center = business / policy, edges = adapters Compile-time deps Out → In (handlers import services, …) Only “inside” code is imported; domain never imports infra Testability Unit-test per layer; integration required for real behaviour Pure use-case tests with mocks; adapters test separately Change impact Changing DB often bubbles up (repo ↔ service ↔ handler) Swap adapters w/o touching core use-case code Learning curve Lower (people already know it) Slightly higher (ports/interfaces design) Typical LOC overhead Smaller for small projects Adds interfaces & folders (~10-15 % extra LOC) Gateway fit? OK for tiny edge proxy Excellent for API gateway with auth, rate-limit, metrics, feature flags Go community use CRUD web apps, REST boilerplates Popular in micro-service, DDD or high-growth codebases (Go-Kit, Go-Clean-Arch, Kratos, Traefik, Caddy) - When to pick which
Pick Layered IF • Prototype / PoC, < 3 months life-span
• < ~5 core use-cases, one protocol, no serious domain rules
• Same team owns all layers (no separate platform team)Pick Hexagonal IF • You expect multiple adapters: HTTP, gRPC, maybe GraphQL later
• You need to plug in/out policies (authN, authZ, RBAC, A/B traffic)
• You care about pure unit tests and CI speed
• Multiple teams will touch the code (domain vs platform)
• Vendor / infra may change (Istio today, Envoy tomorrow, Redis → Memcached, etc.)- Concrete directory layout in Go
Hexagonal skeleton:
/cmd/gateway → main.go, wire DI, env parsing /internal /app → use-cases (ports & interactor structs) └─ auth.go └─ rate_limit.go /domain → entities & value objects (Token, Policy) /adapter /http → handlers & middleware (delivery) /grpc → grpc services (optional) /repo → cache, sql, redis, etc. /proxy → wrapper around httputil.ReverseProxy /pkg → public client SDK (if any)Layered skeleton (simpler):
/cmd/gateway /internal /handler → HTTP handlers (REST/grpc) /service → business + orchestrations /repository → DB, cache, remote calls- Example of dependency direction
Hexagonal:
┌────────────┐ │ Handler │ adapter depends on port └────┬───────┘ ▼ ┌────────────┐ │ Port │ interface in /app └────┬───────┘ ▼ ┌────────────┐ │ Use-Case │ pure Go, zero HTTP └────┬───────┘ ▼ ┌────────────┐ implements port │ Repo impl │ (DB, Redis) └────────────┘Layered:
Handler → Service → Repository ^ | └──────── db models ◄─────┘So a repository change will force recompilation of everything above in layered; not so in hexagonal.
- Minimal code tease
Hexagonal (authorizer port):
// app/port/authorizer.go package port import "net/http" type Authorizer interface { Authorize(*http.Request) error }HTTP adapter implements & uses it:
// adapter/http/auth_mw.go func AuthMiddleware(a port.Authorizer, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if err := a.Authorize(r); err != nil { http.Error(w, "unauthorized", http.StatusUnauthorized) return } next.ServeHTTP(w,r) }) }Swap for gRPC adapter later without touching use-case code.
-
Performance?
No measurable difference. Both compile to the same machine code; the separation is architectural, not runtime. -
Final verdict
• Spinning a quick proof-of-concept or a toy reverse-proxy? → Layered, keep it tiny.
• Building a production gateway that will evolve (multiple protocols, plugins, traffic shaping)? → Hexagonal / Clean. The upfront overhead (~1-2 extra hours to design ports) pays off fast in maintainability and testing.Hope that clears the decision path! If you want an even deeper dive (e.g., wiring with Uber/fx, Google Wire, or go-kit), let me know.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.