So you wrote a Go "library" module X
which:
- you don't want to publish on GitHub or elsewhere
- you want to import and use in your project (the "main" module).
Use a replace
directive along with require
In your main module's go.mod
, add the following lines:
require "X" v0.0.0
replace "X" v0.0.0 => "{local path to the X module}"
The path should point to the root directory of X
. It can be absolute or relative.
To import package util from module X:
import "X/util"
(You don't import modules. You import packages from modules.)
Explanation
Go's module functionality is designed for publicly published modules. Normally, a module's name is both its unique identifier and the path to its public repo. When your go.mod declares a module dependency with the require
directive, Go will automatically find and retrieve the specified version of the module at that path.
If, for example, your go.mod
file contains require github.com/some/dependency v1.2.3
, Go will retrieve the module from GitHub at that path. But if it contains require X v0.0.0
, "X" isn't an actual path and you will get the error cannot find module for path X
.
The replace
directive allows you to specify a replacement path for a given module identifier and version. There are many reasons you'd want to do this, such as to test changes to a module before pushing them to the public repo. But you can also use it to bind a module identifier to local code you don't ever intend to publish.
More details in the Go Modules documentation:
Hope this helps.