Microservices architecture patterns in Go.
1// 1. Strangler Fig: gradual migration2type Router struct {3 legacy http.Handler4 modern http.Handler5}67func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {8 if r.isNewService(req.URL.Path) {9 r.modern.ServeHTTP(w, req)10 } else {11 r.legacy.ServeHTTP(w, req)12 }13}1415// 2. Circuit Breaker: protect against service failures16import "github.com/sony/gobreaker"1718cb := gobreaker.NewCircuitBreaker(gobreaker.Settings{19 Name: "my-service",20 MaxRequests: 3,21 Interval: 10 * time.Second,22 Timeout: 30 * time.Second,23 ReadyToTrip: func(counts gobreaker.Counts) bool {24 return counts.ConsecutiveFailures > 525 },26})2728result, err := cb.Execute(func() (interface{}, error) {29 return callService()30})3132// 3. Retry with backoff33import "github.com/cenkalti/backoff"3435operation := func() error {36 _, err := callService()37 return err38}3940expBackoff := backoff.NewExponentialBackOff()41expBackoff.MaxElapsedTime = 1 * time.Minute4243err := backoff.Retry(operation, expBackoff)4445// 4. API Gateway pattern46type Gateway struct {47 userSvc string48 orderSvc string49 productSvc string50}5152func (g *Gateway) route(req *http.Request) string {53 switch {54 case strings.HasPrefix(req.URL.Path, "/users"):55 return g.userSvc56 case strings.HasPrefix(req.URL.Path, "/orders"):57 return g.orderSvc58 default:59 return g.productSvc60 }61}
Patterns: Strangler Fig, Circuit Breaker, Retry, API Gateway, Saga, CQRS.