Gin的安装
go get -u github.com/gin-gonic/gin
出现问题,应该是有墙的原因
解决办法:
配置代理 可以用阿里云和七牛云等等这里我使用的是七牛云
go env -w GOPROXY=https://goproxy.cn
安装完成
发现爆红情况
原因可能下载不下来,是要手动配置代理
问题解决
Gin使用
启动
ginServer := gin.Default()
ginServer.Run(":8082")
请求以及响应
//访问地址,处理请求 request,response
ginServer.GET("/hello", func(context *gin.Context) {
context.JSON(200, gin.H{"msg": "hello"})
})
从前端发送的json字符串中取值
ginServer.POST("/json", func(context *gin.Context) {
data, _ := context.GetRawData()
var m map[string]interface{}
_ = json.Unmarshal(data, m) //从json中取值
context.JSON(http.StatusOK, m)
})
从 /user?userid=1&name=2 取数据
ginServer.GET("/user", func(context *gin.Context) {
userid := context.Query("userid")
name := context.Query("name")
context.JSON(http.StatusOK, gin.H{
"userid": userid,
"name": name,
})
})
从 /user/1/2 中取
ginServer.GET("/user/:userid/:name", func(context *gin.Context) {
userid := context.Param("userid")
name := context.Param("name")
context.JSON(http.StatusOK, gin.H{
"userid": userid,
"name": name,
})
})
路由
重定向
ginServer.GET("/test", func(context *gin.Context) {
//从定向 301
context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
})
路由组
//路由组
userGroup := ginServer.Group("/user")
{
userGroup.GET("add", func(context *gin.Context) {
xxxx
})
userGroup.GET("login")
userGroup.GET("logout")
}