How to Implement API Gateway Pattern in Go

Web
Implement an API Gateway in Go by using http.ServeMux to route requests to backend services based on URL paths.

Implement the API Gateway pattern in Go by creating a central http.Handler that routes incoming requests to specific backend services based on URL paths. Use http.ServeMux to define routes and http.Client to forward requests to your internal microservices.

package main

import (
	"net/http"
	"time"
)

func main() {
	mux := http.NewServeMux()
	client := &http.Client{Timeout: 5 * time.Second}

	// Route /users to the user service
	mux.HandleFunc("/users/", func(w http.ResponseWriter, r *http.Request) {
		proxyRequest(w, r, "http://localhost:8081", client)
	})

	// Route /orders to the order service
	mux.HandleFunc("/orders/", func(w http.ResponseWriter, r *http.Request) {
		proxyRequest(w, r, "http://localhost:8082", client)
	})

	http.ListenAndServe(":8080", mux)
}

func proxyRequest(w http.ResponseWriter, r *http.Request, target string, client *http.Client) {
	// In a real implementation, you would modify r.URL to point to target
	// and handle headers, body streaming, and response copying here.
	// This is a simplified placeholder for the routing logic.
	w.WriteHeader(http.StatusNotImplemented)
}

This code sets up a basic gateway that listens on port 8080 and routes /users/* to one service and /orders/* to another. You must implement the proxyRequest function to handle the actual HTTP forwarding, including copying request bodies and headers.