Packages and Module
-
Go, packages and modules serve distinct but related roles in organizing and managing code
Module(Big, Complete Project) | Package(Small) | |||
---|---|---|---|---|
What | Entire project is a Go module, managed by the go.mod file. This is Collection of Go packages | A directory is automatically considered a package by Go. So package is directory containing 1 or more Go source files. Every Go source file belongs to a package, declared at the beginning of the file using package `packagename`. | ||
Creation |
Command creates a go.mod file that defines your module path & initializes it
|
|
||
Examples |
|
import statement
- import keyword is used to include external packages/modules in Go program.
import "fmt"
or
import ( //import multiple packages
"fmt"
"math"
)
// Use functions in package using dot statement
fmt.Println("Hello, world!")
go.mod file
-
List all externally hosted packages which require operation(like go get
When you run a command like `go get github.com/user/repo`, the Go tooling will fetch the module from that location
$ go.mod
/*Specifies the the module's path*/
module test
go 1.0
/*lists the specific versions of all dependencies required by the module
It helps ensure that the correct versions of dependencies are used
*/
require (
github.com/auth0/go-jwt-middleware/v2 v2.2.1
)
require (
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
)
go.sum file
-
The go build command uses the Go module cache to find dependencies and will not automatically download dependencies
if they are missing.
Once dependency is downloaded entry is created in go.sum file
When 1st time go.mod is modified, you need to run go mod download command to download the module and update the go.sum file
$ go.sum
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
// Need to run after making entry in go.mod
go mod download github.com/shirou/gopsutil/v3
// Then run
go mod tidy
How to add external module to code?
$ main.go
package main
import (
"github.com/shirou/gopsutil/v4/process" //External module for psutil
)
func main() {
..
}
// 1. Go to documentation and find versions
// https://godocs.io/github.com/shirou/gopsutil/v4/process
// https://godocs.io/github.com/shirou/gopsutil/v4/process?view=versions (v4.24.6)
// 2. Add package path & version
$ go.mod
require (
github.com/shirou/gopsutil/v4 v4.24.6
)
// 3. Run command to download and cache in go.sum
$ go mod download github.com/shirou/gopsutil/v4