how to set up private repo in golang

Introduction

Sometimes you need to import private repository in your golang project.
Like you need to import organization common go module but the repository is private.

Setup

  1. Set GOPRIVATE env using go command.
1
go env -w GOPRIVATE='github.com/${YOUR_GITHUB_ORG}/*'
  1. Set gitconfig when go get via ssh or https
  • ssh
1
git config --global url."[email protected]:${YOUR_GITHUB_ORG}/".insteadOf "https://github.com/${YOUR_GITHUB_ORG}/"
  • https
1
git config --global url."https://${GITHUB_TOKEN}@github.com/${YOUR_GITHUB_ORG}/".insteadOf "https://github.com/${YOUR_GITHUB_ORG}/"

Now, you can run go get -u ${YOUR_PRIVATE_REPO}

In Dockerfile

You maybe come across same problem when build docker image.
So you can write Dockerfile like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
FROM golang:alpine AS builder

WORKDIR /src

# because alpine default exclude git command so you must install git.
RUN apk add --no-cache git

ARG GITHUB_TOKEN
ARG YOUR_GITHUB_ORG

# setup GOPRIVATE env via go
RUN go env -w GOPRIVATE="github.com/${YOUR_GITHUB_ORG}/*"

# setup git config
RUN git config --global url."https://${GITHUB_TOKEN}@github.com/${YOUR_GITHUB_ORG}/".insteadOf "https://github.com/${YOUR_GITHUB_ORG}/"

COPY go.mod go.sum ./
RUN go mod download

COPY cmd ./cmd
COPY internal ./internal
COPY api ./api

ARG APP_NAME

RUN go build -o app ./cmd/${APP_NAME}

FROM alpine:3 AS final

RUN apk add --no-cache tzdata

WORKDIR /app

COPY --from=builder /src/app ./

ENTRYPOINT ./app