我通过运行以下命令初始化go项目:
go mod init firstgo_app
我确认模块已创建:
cat go.mod
module firstgo_app
go 1.18
然后我在github上安装了一个依赖项.com/gin-gonic/gin-by-executing
get github.com/gin-gonic/gin
之后我看了go.mod
的内容,这次是这样的:
cat go.mod
module firstgo_app
go 1.18
require (
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.7.7 // indirect
github.com/go-playground/locales v0.13.0 // indirect
github.com/go-playground/universal-translator v0.17.0 // indirect
github.com/go-playground/validator/v10 v10.4.1 // indirect
github.com/golang/protobuf v1.3.3 // indirect
github.com/json-iterator/go v1.1.9 // indirect
github.com/leodido/go-urn v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect
github.com/ugorji/go/codec v1.1.7 // indirect
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 // indirect
gopkg.in/yaml.v2 v2.2.8 // indirect
)
我不明白的是,所有依赖项都被标记为indirect.我的理解是,只有传递依赖项被标记为indirect,但我直接依赖的依赖项不应该被标记为indirect.那就是github.com/gin-gonic/gin v1.7.7 // indirect
不应该有indirect标签,因为这是我专门下载的依赖项.
我认为是这样的,因为我没有直接使用依赖项,所以我再次创建了模块,但也创建了一个main.go
文件,其中我明确依赖gonic/gin
:
cat main.go
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
当我try 构建时,失败的原因是:
go build
main.go:2:8: no required module provides package github.com/gin-gonic/gin; to add it:
go get github.com/gin-gonic/gin
但当我运行go get github.com/gin-gonic/gin
然后构建时,go.mod
中的所有依赖项仍然被标记为间接.
那又有什么好处呢?我错过了什么?还是我错误地理解了indirect?