引入gin

go get -u github.com/gin-gonic/gin

要是安装太慢或失败,添加代理重新下载安装
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
安装显示

可通过go env 查看配置的两个代理变量

报错: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中移出即可

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")
}

请求返回结果

网友评论