引入gin
![](https://img.haomeiwen.com/i27014196/899c894168df18c5.png)
go get -u github.com/gin-gonic/gin
![](https://img.haomeiwen.com/i27014196/149949fcc5e9fe6b.png)
要是安装太慢或失败,添加代理重新下载安装
go env -w GO111MODULE=on
#下面二选一
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/
go env -w GOPROXY=https://goproxy.io,direct
go get -u github.com/gin-gonic/gin
安装显示
![](https://img.haomeiwen.com/i27014196/b931dff4f4e0637f.png)
可通过go env 查看配置的两个代理变量
![](https://img.haomeiwen.com/i27014196/7a30fc7552af3a1c.png)
报错:gotest.go:4:2: 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
报错:$GOPATH/go.mod exists but should not
产生原因:开启模块支持后,并不能与GOPATH中移出即可
![](https://img.haomeiwen.com/i27014196/cc1b28bfa23f40fa.png)
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
// 创建一个默认的路由引擎
router := gin.Default()
// GET:请求方式;/hello:请求的路径
// 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数
router.GET("/hello", func(c *gin.Context) {
// c.JSON:返回JSON格式的数据
c.JSON(200, gin.H{
"message": "Hello world!",
})
})
router.GET("/name", func(c *gin.Context) {
c.String(200,"hello world")
})
// 启动HTTP服务,默认在0.0.0.0:8080启动服务
router.Run(":8001")
}
![](https://img.haomeiwen.com/i27014196/6a22dc4c8c3f6571.png)
请求返回结果
![](https://img.haomeiwen.com/i27014196/9e7a7f4ab4bb524a.png)
网友评论