生成项目
创建一个目录作为 GO 项目目录。然后进入该目录并初始化项目。
cd test1
go mod init test1
目录下会生成模块配置文件go.mod,其中包含模块名称和版本。
module test1
go 1.13
使用Module
Go Module有以下作用:
- 用于获取外部包的依赖关系管理。
- 解析自定义包作为GOPATH的替代。
- 包版本管理和发布。
依赖外部包
创建一个简单的 go 程序,在其中使用 jsoniter 来生成json 。
package main
import (
"fmt"
jsoniter "github.com/json-iterator/go"
)
type TestInfo struct {
Message string
}
func main() {
info := TestInfo {
Message: "Hahaha",
}
json, _ := jsoniter.Marshal(&info)
fmt.Println(string(json))
}
执行 go run 或者 go build 即可触发依赖解析。
go build test.go
执行完毕后,发现在目录下出现了 go.sum 和 test.exe 文件。test.exe 即为可执行文件, go.sum 包含特定模块版本内容的预期加密校验和。
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.8
...
再次查看 go.mod ,也会发现多了一行内容。
module test1
go 1.13
require github.com/json-iterator/go v1.1.8 // indir
依赖自定义包
在项目中创建 handlers 目录,在其中创建 controller.go 文件并添加如下代码。注意 ShowInfo 方法开头字母大写方便外部引用。
package controller
import "fmt"
func ShowInfo() {
fmt.Println("from other package controller")
}
修改原来的 test.go 文件代码。
package main
import (
"fmt"
controller "test1/handlers"
jsoniter "github.com/json-iterator/go"
)
type TestInfo struct {
Message string
}
func main() {
info := TestInfo {
Message: "Hahaha",
}
json, _ := jsoniter.Marshal(&info)
fmt.Println(string(json))
controller.ShowInfo()
}
执行 go build 命令,可以看到生成了 test1.exe 可执行文件。







网友评论