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())
}
- Create the root module and initialize the project with
go mod init my-service. - Create the
cmd/my-servicedirectory and add themain.goentry point file. - Create the
internaldirectory to hold private packages likehandlerandconfig. - Implement your business logic in
internal/handlerand configuration loading ininternal/config. - Run the service locally using
go run ./cmd/my-service.