Golang modules + Private Git Repo (your own remote server) + SSH

Posted on Dec 20, 2019

Golang modules expect that the imported values be hosted elsewhere. While you can use the "replace" feature in order to point imports to files on your local filesystem, it is better to set up remote storage of your project if possible. In the event you do not want to store your data on a service like github, you simply need a server with git installed, where you can push your work history.

Default 'go get' Behavior

When 'go get' is used to download remote imports, it has predefined behavior defined for certain urls.

Import paths

With your own private packages that are stored on a remote server, you can indicate what kind of version control system your import is using by adding a suffix to your import path. For instance, if your remote server stores your library project at /home/repository/git/my-library, then you would specify your import in your code as follows:

import "my-service.com/my-library.git"

If you are accessing a folder below the root of the git repository it would be:

import "my-service.com/my-library.git/folder/here"

This lets 'go get' understand that you are accessing code using the git version control system.

Git insteadOf

Now you can manually add a line to your $HOME/.gitconfig file like so:

[url "ssh://[email protected]:22/home/repository/git/"]
    insteadOf = git://my-service.com/

In this case "109.432.11.23" is the ip address of the remote repository so you will need to change this value as well as the actual path to your actual repository. Notice that since your import starts with my-service.com and because you added a '.git' suffix into the import path, 'go get' would normally trigger connecting to git on the my-service.com server, but we are overriding that behavior in our .gitconfig file. And that is it, go build will trigger remote pulling of the imports on your remote server.

Debugging

One helpful command for debugging the path is

git ls-remote -q ssh://[email protected]:22/home/repository/git/my-library.git

This allows you to see whether or not git can read your remote repository.