How to Structure a Go Microservice Repository

Structure a Go microservice by placing the entry point in cmd/<service> and private logic in internal packages.

Structure a Go microservice repository by separating business logic, HTTP handlers, and configuration into distinct packages under a cmd directory for the entry point. Create a main.go file in cmd/<service-name> that initializes the server and dependencies, then import your internal packages to wire them together.

// cmd/my-service/main.go
package main

import (
	"log"
	"my-service/internal/handler"
	"my-service/internal/config"
)

func main() {
	cfg := config.Load()
	h := handler.New(cfg)
	log.Fatal(h.Serve())
}
  1. Create the root module and initialize the project with go mod init my-service.
  2. Create the cmd/my-service directory and add the main.go entry point file.
  3. Create the internal directory to hold private packages like handler and config.
  4. Implement your business logic in internal/handler and configuration loading in internal/config.
  5. Run the service locally using go run ./cmd/my-service.