Initialize Go Module with Proper Structure
Beginner10 minTrending
Set up a new Go project with module initialization, standard directory layout, and essential boilerplate files.
Prerequisites
- -Go 1.21+ installed
Steps
1
Create project directory and initialize module
Create a new directory and initialize a Go module with your module path.
$ mkdir myapp && cd myapp && go mod init github.com/yourname/myapp
Use your GitHub path as the module name for easy import by others.
2
Create standard directory layout
Set up the conventional Go project structure with cmd, internal, and pkg directories.
$ mkdir -p cmd/myapp internal/config internal/handler pkg/utils
The internal/ directory prevents external packages from importing its contents.
3
Create the main entry point
Write a minimal main.go file in the cmd directory as the application entry point.
$ cat > cmd/myapp/main.go << 'EOF'
package main
import "fmt"
func main() {
fmt.Println("Hello from myapp")
}
EOF
4
Add a Makefile for common tasks
Create a Makefile with build, test, and lint targets for a consistent developer workflow.
$ cat > Makefile << 'EOF'
.PHONY: build test lint run
build:
go build -o bin/myapp ./cmd/myapp
test:
go test ./... -v
lint:
golangci-lint run ./...
run:
go run ./cmd/myapp
EOF
5
Build and run the project
Verify the setup by building and running the application.
$ go build -o bin/myapp ./cmd/myapp && ./bin/myapp
Full Script
FAQ
Discussion
Loading comments...