Accessing local packages within a go module (go 1.11)
Solution 1:
Let me define this first modules
are collections of packages
. In Go 11, I use go modules like the following:
If both packages are in the same project, you could just do the following:
In go.mod
:
module github.com/userName/moduleName
and inside your main.go
import "github.com/userName/moduleName/platform"
However, if they are separate modules, i.e different physical paths and you still want to import local packages
without publishing this remotely to github for example, you could achieve this by using replace
directive.
Given the module name github.com/otherModule
and platform
, as you've called it, is the only package inside there. In your main module's go.mod
add the following lines:
module github.com/userName/mainModule
require "github.com/userName/otherModule" v0.0.0
replace "github.com/userName/otherModule" v0.0.0 => "local physical path to the otherModule"
Note: The path should point to the root directory of the module, and can be absolute or relative.
Inside main.go
, to import a specific package like platform
from otherModule
:
import "github.com/userName/otherModule/platform"
Here's a gentle introduction to Golang Modules
Solution 2:
I would strongly suggest you to use go toolchain which takes care of these issues out of the box. Visual Studio Code with vscode-go plugin is really useful.
Problem here is that Go requires relative paths with respect to your $GOPATH/src
or module
in import statement. Depending on where you are in your GOPATH
, import path should include that as well. In this case, import statement must include go module path in go.mod
GOPATH
Assume your project resides here:
$GOPATH/src/github.com/myuser/myproject
Your import path should be:
import "github.com/myuser/myproject/platform"
VGO
Assume your go.mod file is:
module example.com/myuser/myproject
Your import path should be:
import "example.com/myuser/myproject/platform"
Solution 3:
As someone new to go I didn't immediately understand the accepted answer – which is great, by the way. Here's a shorter answer for those very new people!
In go modules/packages are expressed as urls that you import in your code:
import your.org/internal/fancy_module
But wait! My code isn't at a url, what's happening??
This is the cleverness of go. You pretend there's a url even when there isn't one. Because:
- This makes including easier as no matter where your file is located the import uses the same url (the code stays the same even if the files move!)
- You can have packages that having naming conflicts. So
google.com/go-api/user
doesn't conflict with the definitions atyour.org/internal/user
- Someday you might publish a url on GitHub and all the code will just work
That's all great Evan, but how do I import a relative path?
Good question! You can import by changing your go.mod
file to have this line:
module fancy_module
go 1.16
replace your.org/fancy_module => ../path/to/fancy_module