How to Design Microservices in Go

Web
Design Go microservices by building independent binaries with HTTP handlers, context-aware cancellation, and graceful shutdown logic.

Design microservices in Go by defining small, single-responsibility binaries that communicate via HTTP or gRPC and share no state. Start by creating a new module, implementing a handler that accepts a context for cancellation, and running the server with graceful shutdown support.

package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	server := &http.Server{
		Addr:    ":8080",
		Handler: mux,
	}

	go func() {
		log.Println("Server starting on :8080")
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("ListenAndServe: %v", err)
		}
	}()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	log.Println("Shutting down server...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := server.Shutdown(ctx); err != nil {
		log.Fatalf("Server forced to shutdown: %v", err)
	}
	log.Println("Server exited")
}
  1. Initialize the module with go mod init example.com/microservice.
  2. Create a main.go file containing the HTTP server and signal handling logic shown above.
  3. Run the service locally using go run main.go.
  4. Build a static binary for deployment with go build -o microservice main.go.
  5. Deploy the binary to your container orchestration platform.