Gin快速入门及注意事项
Go的web框架有很多,比如:Gin、Iris等,今天我们主要介绍Gin
1 环境搭建
- 设置代理
# 开启module功能【go的版本是1.13以上】
go env -w GO111MODULE=on
# 设置代理
go env -w GOPROXY=https://goproxy.io,direct
- Goland中设置好GoROOT、GoPath
- Go安装依赖的方式是通过
go get
,其本质是通过git clone,因此本地需要有git环境,如果没有,参考git安装步骤。- 安装辅助类库
git clone https://github.com/golang/tools.git $GOPATH/src/golang.org/x/tools
go get -v github.com/ramya-rao-a/go-outline
go get -v github.com/sqs/goreturns
go get -v github.com/rogpeppe/godef
- 安装Gin
go get -u -v github.com/gin-gonic/gin
2 入门案例及RESTFul
2.1 入门案例
- 代码
package main
import "github.com/gin-gonic/gin"
func main() {
//创建一个服务
ginServer := gin.Default()
ginServer.Use()
//TODO 连接数据库的代码
//访问地址,处理我们的请求 Request Response
/*
1. “/hello” 处理请求地址
2. func(context *gin.Context) {} 处理请求
3. context.JSON() 响应JSON数据
*/
ginServer.GET("/hello", func(context *gin.Context) {
context.JSON(200, gin.H{"msg": "hello gin"})
})
//服务器端口【注意:端口前面有一个冒号】
ginServer.Run(":8082")
}
2.2 RESTFul
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
ginServer := gin.Default()
ginServer.Use()
/*
RESTFul:相同的请求路径,根据不同的请求方法来标识不同的操作
GET:获取资源
POST:新增
PUT:修改
DELETE:删除
*/
//POST
ginServer.POST("/user", func(context *gin.Context) {
//处理新增用户逻辑
context.JSON(http.StatusOK, gin.H{"msg": "新增用户成功"})
})
ginServer.DELETE("/user", func(context *gin.Context) {
//处理删除用户
context.JSON(http.StatusOK, gin.H{"msg": "删除用户成功"})
})
ginServer.PUT("/user", func(context *gin.Context) {
//处理更新用户
context.JSON(http.StatusOK, gin.H{"msg": "更新用户成功"})
})
ginServer.Run(":8082")
}
- POST:
3 响应页面
- main.go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
ginServer := gin.Default()
ginServer.Use()
//加载静态页面
//加载所有静态页面
ginServer.LoadHTMLGlob("src/template/*")
//ginServer.LoadHTMLFiles("src/template/index.html") //加载指定文件
//加载静态资源【css、js等】
ginServer.Static("/static", "src/static")
//响应一个页面给前端
ginServer.GET("/index", func(context *gin.Context) {
//context.JSON() 响应JSON数据
//响应状态码 http.StatusOK = 200
context.HTML(http.StatusOK, "index.html", gin.H{
"msg": "这是go后台传过来的数据",
})
})
//服务器端口
ginServer.Run(":8082")
}
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>这是index</title>
<link rel="stylesheet" href="../static/css/index.css">
<script src="../static/js/index.js"></script>
</head>
<body>
hello, this is index.html, you know?
<p>接收后台返回的数据:{{.msg}}</p>
</body>
</html>
- index.js
alert("success...")
- index.css
body{
color: aquamarine;
}
4 获取请求参数
package main
import (
"encoding/json"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
ginServer := gin.Default()
ginServer.Use()
//接收前端传过来的参数
//1.PathVariable xxx?userid=1&username=zhangsan
ginServer.GET("/user/info", func(context *gin.Context) {
userid := context.Query("userid")
username := context.Query("username")
context.JSON(http.StatusOK, gin.H{
"userid": userid,
"username": username,
"msg": "接收pathvariable参数成功",
})
})
//2.Param xxx/user/info/1/zhangsan
ginServer.GET("/user/info/:userid/:username", func(context *gin.Context) {
//与路径前端的名称对应
userid := context.Param("userid")
username := context.Param("username")
context.JSON(http.StatusOK, gin.H{
"userid": userid,
"username": username,
"msg": "接收param参数成功",
})
})
//3. JSON参数
ginServer.POST("/json", func(context *gin.Context) {
data, _ := context.GetRawData()
var m map[string]interface{}
//将前端传入的json数据反序列化,然后赋值给m;返回的结果是无序的,因为go中的map本身是无序的
_ = json.Unmarshal(data, &m)
context.JSON(http.StatusOK, m)
})
//4. 表单数据
ginServer.POST("/user/add", func(context *gin.Context) {
username := context.PostForm("username")
password := context.PostForm("password")
context.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
"msg": "处理表单数据成功",
})
})
ginServer.Run(":8082")
}
5 路由讲解
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//路由
ginServer := gin.Default()
ginServer.Use()
ginServer.LoadHTMLGlob("src/template/*")
//1. 重定向
ginServer.GET("/testRedirect", func(context *gin.Context) {
//重定向状态码:301
context.Redirect(http.StatusMovedPermanently, "www.baidu.com")
})
//2. 404 NoRoute
ginServer.NoRoute(func(context *gin.Context) {
//nil :返回数据为空
context.HTML(http.StatusNotFound, "404.html", nil)
})
//3. 路由组【类似于java中在类上添加RequestMapping】
userGroup := ginServer.Group("/user")
{
userGroup.GET("/info", func(context *gin.Context) {
//TODO 接收请求处理数据
})
//请求路径: localhost:8082/user/update
userGroup.PUT("/update")
userGroup.POST("/add")
}
orderGroup := ginServer.Group("/order")
{
orderGroup.GET("/info")
orderGroup.DELETE("/delete")
}
ginServer.Run(":8082")
}
6 中间件(拦截器)
package main
import (
"github.com/gin-gonic/gin"
"log"
"net/http"
)
// 自定义go中间件 拦截器
func myHandler() gin.HandlerFunc {
return func(context *gin.Context) {
//通过自定义的中间件设置的值,在后续处理只要调用了这个中间件的都可以拿到这里设置的参数
//可以用于设置参数、鉴权等
context.Set("hasPrivilege", true)
context.Next() //放行
//context.Abort() //阻止
}
}
func main() {
ginServer := gin.Default()
ginServer.Use()
// xxx?username=郭艾伦&age=27
//myHandler() 如果此处不指定使用myHandler,则所有方法都生效【全局生效】
ginServer.GET("/user/info", myHandler(), func(context *gin.Context) {
//取出中间件的值
username := context.Query("username")
age := context.Query("age")
hasPrivilege := context.MustGet("hasPrivilege")
log.Println("hasPrivilege:", hasPrivilege)
context.JSON(http.StatusOK, gin.H{
"username": username,
"age": age,
})
})
ginServer.Run(":8082")
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/148507.html