GitLab CI Pipeline for Go Projects

GitLab CI configuration for Go projects with vet, test with race detection, and static binary building. Includes module caching for fast builds.

Language Pipelines

Detailed Explanation

Go CI Pipeline in GitLab

Go projects benefit from module caching and the ability to produce static binaries that can be deployed as single-file artifacts.

Pipeline Configuration

stages:
  - lint
  - test
  - build

variables:
  GOPATH: "$CI_PROJECT_DIR/.go"
  GOFLAGS: "-mod=readonly"

vet:
  stage: lint
  image: golang:1.22-alpine
  script:
    - go vet ./...
  cache:
    key: go-modules
    paths:
      - .go/pkg/mod/
    policy: pull-push

test:
  stage: test
  image: golang:1.22-alpine
  script:
    - go test -race -coverprofile=coverage.out ./...
    - go tool cover -func=coverage.out
  cache:
    key: go-modules
    paths:
      - .go/pkg/mod/
    policy: pull-push
  artifacts:
    paths:
      - coverage.out
    expire_in: 30 days

build:
  stage: build
  image: golang:1.22-alpine
  script:
    - CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o app ./cmd/server
  cache:
    key: go-modules
    paths:
      - .go/pkg/mod/
    policy: pull
  artifacts:
    paths:
      - app
    expire_in: 1 week

Key Points

GOPATH redirection: Like Python's pip cache, setting GOPATH inside the project directory allows module caching across pipeline runs.

-race flag: The race detector catches concurrent access bugs at test time. It adds overhead but is essential for CI pipelines.

Static binary: CGO_ENABLED=0 produces a fully static binary with no C library dependencies, perfect for scratch or distroless Docker images.

-ldflags="-s -w": Strips debug symbols and DWARF information, reducing binary size by 20-30%.

Use Case

Suitable for Go microservices, CLI tools, and libraries. The static binary output can be directly used in minimal Docker images or deployed to serverless platforms.

Try It — GitLab CI Config Generator

Open full tool