I've created a library as the module for personal use outside of "GOPATH" in "database" folder with this command "go mod init database," and I don't know:
- How to use/import this module in another module?
OS: Windows 7, Go: v1.11
I've created a library as the module for personal use outside of "GOPATH" in "database" folder with this command "go mod init database," and I don't know:
OS: Windows 7, Go: v1.11
The easiest and working out-of-the-box solution is to put your
database
package / module into a VCS (e.g. github.com), so other packages (inside other modules) can simply refer to it by importing it like:If you do so, you don't even have to fiddle with the
go.mod
files manually, everything will be taken care of by the go tool: it will automatically recognize and resolve this dependency, download and install the required package, and will also updatego.mod
automatically.Staying entirely on local disk
If you don't want to use a VCS (e.g. you're just experimenting or you haven't decided what to use yet), then you can still do it. The how is detailed in the official Go Wiki: Can I work entirely outside of VCS on my local filesystem?
So you created a
database
folder outside ofGOPATH
, and you created a module in it. And you created another module, let's call itmain
, and you want to use thisdatabase
package.What you must do is:
go.mod
of yourmain
module must list thedatabase
package as a "requirement". Give a temporary VCS name to yourdatabase
package:You must tell the go tool where this package is located, because the full package name we used is just a temporary / fantasy name. Use the
replace
directive to make thisdatabase
package point to a folder on your local disk; you may use absolute and relative paths:And that's all.
Working example
Let's see a working example. Let's create a
pretty
module. Create apretty
folder with 2 files in it:pretty.go:
go.mod (can be created by running
go mod init pretty
):Now let's create another, main module. Let's create a folder
osinf
(it may be whatever) next to thepretty
folder. 2 files in it:osinf.go (note we intend to use our
pretty
package / module, we import it by"example.com/me/pretty"
):go.mod:
And that's all.
Running
go run osinf.go
in theosinf
folder, the output is: