一、GO环境安装
【Golang】(二)Go语言环境安装_安装golang 环境-CSDN博客
二、Gin介绍
Gin 是一个 Go (Golang) 编写的轻量级 http web 框架,运行速度非常快,如果你是性能和高效的追求者,我们推荐你使用 Gin 框架。
Gin 最擅长的就是 Api 接口的高并发,如果项目的规模不大,业务相对简单,这个时候我们也推荐您使用 Gin。
当某个接口的性能遭到较大挑战的时候,这个还是可以考虑使用 Gin 重写接口。
Gin 也是一个流行的 golang Web 框架,Github Start 量已经超过了 50k。
Gin 的官网:https://gin-gonic.com/zh-cn/
Gin Github 地址:https://github.com/gin-gonic/gin
三、Gin 环境搭建
要安装 Gin 软件包,需要先安装 Go 并设置 Go 工作区。
例如mac下如下设置
export GOROOT=/usr/local/go
export PATH=$PATH:$GOROOT/bin:$GOBIN
export GOPATH=/Users/mac/data/devwork/go-work
export GOPROXY=https://goproxy.cn,direct
1、下载并安装 Gin
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
go mod init "自己项目的项目名"
go get -u github.com/gin-gonic/gin
2、将 Gin 引入到代码当中
import "github.com/gin-gonic/gin"
3、新建 Main.go 配置路由
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
// 创建一个默认的路由引擎
ginServer := gin.Default()
// 配置路由
ginServer.GET("/", func(context *gin.Context) {
context.JSON(200, gin.H{
"msg": "Hello world!",
})
})
// 启动 HTTP 服务,默认在 0.0.0.0:8080启动服务
ginServer.Run()
// ginServer.Run(":8081") 使用8081端口启动服务
}
4、在浏览器地址栏中输入localhost:8080
四、问题排查
1、解决$GOPATH/go.mod exists but should not 或者 下载module时连接超时
解决方法
1)方法1
临时执行如下设置命令
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
2)方法2
在环境变量中设置GOPROXY
export GOPROXY=https://goproxy.cn,direct
推荐使用方法2.