[英]How to install Gin with Golang
I'm a newbie on Golang, and I'm trying to use Gin to develop a web server on Ubuntu 16.04.我是 Golang 的新手,我正在尝试使用Gin在 Ubuntu 16.04 上开发 web 服务器。
After executing go get -u github.com/gin-gonic/gin
, many folders appear at ~/go/pkg/mod/github.com/
.执行
go get -u github.com/gin-gonic/gin
后,在~/go/pkg/mod/github.com/
出现很多文件夹。
Then I try to make an example:然后我试着举个例子:
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 (for windows "localhost:8080")
}
However, go run example.go
made the error:但是,
go run example.go
出现错误:
example.go:3:8: cannot find package "github.com/gin-gonic/gin" in any of:
/usr/local/go/src/github.com/gin-gonic/gin (from $GOROOT)
/home/zyh/go/src/github.com/gin-gonic/gin (from $GOPATH)
In my system, $GOROOT
is /usr/local/go/
and $GOPATH
is ~/go/
.在我的系统中,
$GOROOT
是/usr/local/go/
并且$GOPATH
是~/go/
。
How could I solve this problem?我该如何解决这个问题?
For Go version 1.11 or newer, You should use Go Modules .对于 Go 版本 1.11 或更高版本,您应该使用Go 模块。
If you are just starting with Go, you should start with the newer version.如果您只是从 Go 开始,您应该从较新的版本开始。 I think you are using a Go version that supports go modules already because the modules you are trying to get are downloading to
~/go/pkg/mod/
directory.我认为您正在使用支持 go 模块的 Go 版本,因为您尝试获取的模块正在下载到
~/go/pkg/mod/
目录。
go mod init your-project-name
This will create a go.mod
file in your project directory.这将在您的项目目录中创建一个
go.mod
文件。
go mod tidy
This will fill up the go.mod
file with appropriate modules and create a go.sum
in your project directory.这将使用适当的模块填充
go.mod
文件,并在您的项目目录中创建go.sum
。 The go.sum contains expected cryptographic hashes of each module version. go.sum 包含每个模块版本的预期加密哈希。
After that, the go run example.go
command should run the program without any issues.之后,
go run example.go
命令应该运行程序没有任何问题。
go mod vendor
This will bring all the vendors to your projects /vendor
directory so that you don't need to get the modules again if working from another machine on this project.这会将所有供应商带到您的项目
/vendor
目录,这样如果在该项目的另一台机器上工作,您就不需要再次获取模块。
I realized that after adding a package called gopls
, my IDE is working perfectly.我意识到在添加一个名为
gopls
的 package 后,我的 IDE 工作正常。
Install gopls
using snap: sudo snap install gopls --classic
使用 snap 安装
gopls
: sudo snap install gopls --classic
From the error, you can see that GOPATH is your '/home/zyh/go' not your ~/go.从错误中,您可以看到 GOPATH 是您的 '/home/zyh/go' 而不是您的 ~/go。 and you can run shell
go env
to confirm where is your GOPATH?你可以运行 shell
go env
来确认你的 GOPATH 在哪里? then modify it.然后修改它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.