I\'ve used GOPATH
but for this current issue I\'m facing it does not help. I want to be able to create packages that are specific to a project:
You can use replace
go mod init example.com/my/foo
foo/go.mod
module example.com/my/foo
go 1.14
replace example.com/my/bar => /path/to/bar
require example.com/my/bar v1.0.0
foo/main.go
package main
import "example.com/bar"
func main() {
bar.MyFunc()
}
bar/go.mod
module github.com/my/bar
go 1.14
bar/fn.go
package github.com/my/bar
import "fmt"
func MyFunc() {
fmt.Printf("hello")
}
Importing a local package is just like importing an external pacakge
except inside the go.mod file you replace that external package name with a local folder.
The path to the folder can be full or relative /path/to/bar
or ../bar
I have a similar problem and the solution I am currently using uses Go 1.11 modules. I have the following structure
- projects
- go.mod
- go.sum
- project1
- main.go
- project2
- main.go
- package1
- lib.go
- package2
- lib.go
And I am able to import package1 and package2 from project1 and project2 by using
import (
"projects/package1"
"projects/package2"
)
After running go mod init projects
. I can use go build
from project1 and project2 directories or I can do go build -o project1/exe project1/*.go
from the projects directory.
The downside of this method is that all your projects end up sharing the same dependency list in go.mod. I am still looking for a solution to this problem, but it looks like it might be fundamental.