Setting up GitAction private repository access for Golang applications

Recently, i’ve been working on a Go project that has dependencies on internal/private packages built in-house by the team, mostly to cut boilerplate or automate recurring processes. We’re using go.mod to manage this project’s dependencies. One problem i & other member of the team often encounter is the GitAction error whenever we tried to access private repository/package from inside the project, most especially in Dockerfile(s) or some simple ci checks. The solution to this problem is quite simple, even though it skipped my memory almost anytime i had to do it. This write-up is a small documentation for myself(easy future reference when i forget again :) ) and anyone out there facing similar issue.

An Example GitAction

Below is an example of one of the many steps we have in the project’s GitAction:

 1# ci.yml
 2name: Build
 3on:
 4  push:
 5    branches:
 6      - *
 7  pull_request:
 8    branches: [*]
 9
10jobs:
11
12  lint:
13    name: Build to prevent compiler error
14
15    # The type of runner that the job will run on
16    runs-on: ubuntu-latest
17
18    steps:
19      # Setup Go
20      - name: Set up Go
21        uses: actions/setup-go@v2
22        with:
23          go-version: ^1.15
24
25      - name: Check out code
26        uses: actions/checkout@v2
27
28      - name: Run build
29        run: go build .

The above GitAction manifest is very simple, it builds a Go application to check for general compilation issues e.g unused variables or missed syntax error. Assuming the project or repository this workflow is meant for requires access to a particular private repository, you would get an error from go.mod when it tries to fetch & resolve all dependencies.

Solution & Requirement

Once you’re able to generate PAT, add the lines below to the existing GitAction manifest, just before the authentication is required.

1    - name: Setup credentials to access private repo
2      run: git config --global url."https://${{ secrets.PAT }}:x-oauth-basic@github.com/".insteadOf "https://github.com/"

The updated ci.yml should look like this:

 1# ci.yaml
 2name: Build
 3on:
 4  push:
 5    branches:
 6      - *
 7  pull_request:
 8    branches: [*]
 9
10jobs:
11
12  lint:
13    name: Build to prevent compiler error
14
15    # The type of runner that the job will run on
16    runs-on: ubuntu-latest
17
18    steps:
19      # Setup Go
20      - name: Set up Go
21        uses: actions/setup-go@v2
22        with:
23          go-version: ^1.15
24
25      - name: Check out code
26        uses: actions/checkout@v2
27
28      - name: Setup credentials to access private repo
29        run: git config --global url."https://${{ secrets.PAT }}:x-oauth-basic@github.com/".insteadOf "https://github.com/"
30
31      - name: Run build
32        run: go build .

And that’s it! You should be able to authenticate with Github from GitAction context from now on. Enjoy :)