DEV Community

BC
BC

Posted on

Golang: go get package from your private repo in Gitlab

#go

We can use go get to install a module from our private repo.

Say we have a private repo gomath that is hosted in gitlab under url: https://gitlab.com/yourname/gomath:

File math.go:

package gomath

func Double(a int) int {
    return a * 2
}
Enter fullscreen mode Exit fullscreen mode

Now in your other Go module you want to install this package, you need to do 2 things:

  1. Set the GOPRIVATE env variable
  2. Set git config to let git know your personal access token in gitlab. You can get the token from gitlab > preferences > Access Tokens. Make sure your token has the "read_repository" scope.

File config.sh:

#!/usr/bin/env bash

go env -w GOPRIVATE=https://gitlab.com/yourname/gomath

git config \
  --global \
  url."https://<yourname>:<personal access token from gitlab>@gitlab.com".insteadOf \
  "https://gitlab.com"
Enter fullscreen mode Exit fullscreen mode

Run this script:

$ bash config.sh
Enter fullscreen mode Exit fullscreen mode

Now under your Go module, you can just use go get like normal:

$ go get https://gitlab.com/yourname/gomath
Enter fullscreen mode Exit fullscreen mode

Then use it in main.go:

package main

import (
    "fmt"

    "gitlab.com/yourname/gomath"
)

func main() {
    num := 2
    result := gomath.Double(num)
    fmt.Println("result:", result)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)