Using Go Modules with GitLab repos

I wanted to share a small trick for using Go 1.11+ modules with GitLab repos. If you just try to import another repo and run a build or test using GitLab CI, this happens:

fatal: could not read Username for 'https://git.dolansoft.org': terminal prompts disabled

Go (calling Git) complains because it doesn't know how to authenticate itself. GitLab has a cool feature as of 9.0 which grants the GitLab CI token the same access rights as the user that pushed the commit. Now we just need to make Git use that. We cannot pass these credentials in the URL since the call is controlled by Go. But there exists a Git feature which allows us to replace the URL by one of our choosing, including one that contains credentials. The end result looks something like this:

test:
  stage: test
  image: golang:1.12
  script:
    - git config --global url."https://gitlab-ci-token:$CI_BUILD_TOKEN@git.dolansoft.org/".insteadOf "https://git.dolansoft.org/"
    - go test

If you have multiple build steps, you can also put that command into before_script.