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")
}
- Initialize the module with
go mod init example.com/microservice. - Create a
main.gofile containing the HTTP server and signal handling logic shown above. - Run the service locally using
go run main.go. - Build a static binary for deployment with
go build -o microservice main.go. - Deploy the binary to your container orchestration platform.