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))
}
- Create a
configpackage to load environment variables and define a configuration struct. - Create an
internal/handlerpackage to define HTTP handlers and register routes on anhttp.ServeMux. - Create an
internal/servicepackage to encapsulate business logic and database interactions. - In
main.go, instantiate the configuration, initialize the service layer, create handlers with the service, and start the HTTP server.