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
Set GOPRIVATE env using go command.
1 go env -w GOPRIVATE='github.com/${YOUR_GITHUB_ORG}/*'
Set gitconfig when go get via ssh or https
1 git config --global url."[email protected] :${YOUR_GITHUB_ORG}/".insteadOf "https://github.com/${YOUR_GITHUB_ORG}/"
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 builderWORKDIR /src RUN apk add --no-cache git ARG GITHUB_TOKENARG YOUR_GITHUB_ORGRUN go env -w GOPRIVATE="github.com/${YOUR_GITHUB_ORG} /*" 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_NAMERUN go build -o app ./cmd/${APP_NAME} FROM alpine:3 AS finalRUN apk add --no-cache tzdata WORKDIR /app COPY --from=builder /src/app ./ ENTRYPOINT ./app