Build Go project with GitLab CI

In our previous blog post - Manage Go dependencies using Glide, we have a simple Go project to demonstrate dependency management using Glide. Let’s move forward to build the project on GitLab CI.

Before we start

I have created a new project under $GOPATH and copy the all the files from the glide-example. That includes:

  • .gitignore
  • glide.lock
  • glide.yaml
  • README.md (optional)
  • vendor/

Make sure they could be built and run locally.

Setup the pipeline

Let’s start with adding the following pipeline file to the project root folder.

.gitlab-ci.yaml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
stages:
  - build

build:
  stage: build
  image: golang:1.9.2
  before_script:
  script:
    # Compile and name the binary as `hello`
    - go build -o hello
    # Execute the binary
    - ./hello

Commit and push this new .gitlab-ci.yaml file to gitlab. Then check the pipeline job.

Build failed!

Build failed!

The error indicates that the build could not locate the vendor package. This is because the checkout project path of the GitLab CI job is /builds/ykyuen/gitlab-ci-go-build which is not under $GOPATH.

The solution

In order to fix the build error, we have to make sure the project is under $GOPATH. This could be done by creating a symbolic link before starting the build process. Let’s update the .gitlab-ci.yaml.

.gitlab-ci.yaml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
stages:
  - build

build:
  stage: build
  image: golang:1.9.2
  before_script:
    # Create a symbolic link under $GOPATH, this is needed for local build
    # i.e. /go/src/gitlab.com/ykyuen/gitlab-ci-go-build
    - cd $GOPATH/src
    - mkdir -p gitlab.com/$CI_PROJECT_NAMESPACE
    - cd gitlab.com/$CI_PROJECT_NAMESPACE
    - ln -s $CI_PROJECT_DIR
    - cd $CI_PROJECT_NAME
  script:
    # Compile and name the binary as `hello`
    - go build -o hello
    # Execute the binary
    - ./hello

Commit and push the change and try the pipeline job again.

Build succeed!

Build succeed!

Summary

  • Go project should be always under $GOPATH.
  • Checkin the vendor folder could simplify the pipeline as we do not need to run the glide install command.