Since the introduction of go.mod , I think both local and external package management becomes easier. Using go.mod, it is possible to have go project outside the GOPATH as well.
Import local package:
Create a folder demoproject and run following command to generate go.mod file
go mod init demoproject
I have a project structure like below inside the demoproject directory.
├── go.mod
└── src
├── main.go
└── model
└── model.go
For the demo purpose, insert the following code in the model.go file.
package model
type Employee struct {
Id int32
FirstName string
LastName string
BadgeNumber int32
}
In main.go, I imported Employee model by referencing to "demoproject/src/model"
package main
import (
"demoproject/src/model"
"fmt"
)
func main() {
fmt.Printf("Main Function")
var employee = model.Employee{
Id: 1,
FirstName: "First name",
LastName: "Last Name",
BadgeNumber: 1000,
}
fmt.Printf(employee.FirstName)
}
Import external dependency:
Just run go get
command inside the project directory.
For example:
go get -u google.golang.org/grpc
It should include module dependency in the go.mod file
module demoproject
go 1.13
require (
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa // indirect
golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 // indirect
golang.org/x/text v0.3.2 // indirect
google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150 // indirect
google.golang.org/grpc v1.26.0 // indirect
)
https://blog.golang.org/using-go-modules
.go
files in a single directory are part of the same package, and you don't need toimport
files in the same package (i.e., the same directory). You mentioned working outside of GOPATH, which is one of the capabilities of the new Go modules system. This answer covers module structure, importing local packages, arranging packages within a module, whether or not to have multiple modules in single repository, etc.git/repo/to/my/project
path? I just don't see the reason why anyone would want this behavior. What if you move your project to another location (i.e. Docker image), you need to alter all paths again? I'm looking for answers why this is so complicated.