How to Structure a Go Microservice

Web
Structure a Go microservice by separating handlers, business logic, and configuration into distinct packages and initializing them in main.go.

Structure a Go microservice by separating concerns into distinct packages for handlers, business logic, and configuration, then initialize dependencies in main.go before starting the server.

package main

import (
	"log"
	"net/http"
	"your-service/internal/handler"
	"your-service/internal/config"
)

func main() {
	cfg := config.Load()
	h := handler.New(cfg)
	log.Fatal(http.ListenAndServe(cfg.Addr, h.Mux))
}
  1. Create a config package to load environment variables and define a configuration struct.
  2. Create an internal/handler package to define HTTP handlers and register routes on an http.ServeMux.
  3. Create an internal/service package to encapsulate business logic and database interactions.
  4. In main.go, instantiate the configuration, initialize the service layer, create handlers with the service, and start the HTTP server.