1、安装
要使用Gin非常简单,它和其他第三方 Golang 库一样。如果你是基于GOPATH开发的,你需要先使用
go get -u github.com/gin-gonic/gin
下载gin,然后import导入即可。
如果你是用Go Module这种方式,使用import直接导入使用,然后你在go run运行的时候,会自动的下载gin包编译使用。当然你也可以通过go mod tidy来下载依赖的模块。
2、Hello Gin
src 目录下创建hello.go 文件
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"welcome":"hello gin",
})
})
// 启动HTTP服务,默认在0.0.0.0:8080启动服务 、localhost:8080、127.0.0.1:8080
r.Run(":8080")
}
然后我们运行它,
在git bash 下运行
go run hello.go
打开浏览器,输入http://localhost:8080/就可以看到如下内容:
{"welcome":"hello gin"}
3、注意点
3.1、报错:main.go:3:8: cannot find module providing package github.com/gin-gonic/gin: working directory is not part of a module
解决方法,当前目录分别运行下面两句代码:
go mod init gin
go mod edit -require github.com/gin-gonic/gin@latest
原文地址:
https://www.flysnow.org/2019/12/10/golang-gin-quick-start.html