本文介绍Gin 框架的一些常用的用法,包括简单的demo,restfulf风格api,如何接受前端传递的参数,路由处理,拦截器设置
主流Web框架
首先介绍几个比较主流的Go Web框架:
Gin 框架
Gin 是一个用 Go (Golang) 编写的 HTTP Web 框架,封装比较优雅,API友好,源码注释比较明确。具有快速灵活,容错方便等特点,它具有类似 Martini 的 API,但性能比 Martini 快 40 倍。
文档 | Gin Web Framework (gin-gonic.com)
CloudWeGo-Hertz 框架
Hertz[həːts] 是一个 Golang 微服务 HTTP 框架,在设计之初参考了其他开源框架 fasthttp、gin、echo 的优势, 并结合字节跳动内部的需求,使其具有高易用性、高性能、高扩展性等特点,目前在字节跳动内部已广泛使用。 如今越来越多的微服务选择使用 Golang,如果对微服务性能有要求,又希望框架能够充分满足内部的可定制化需求,Hertz 会是一个不错的选择。
Beego 框架
Beego是一个快速开发Go应用的开源框架,被誉为Go语言生态中最活跃的框架之一。它是建立在Go语言基础上的一个轻量级Web框架,旨在通过提供一系列的工具和类库,使您的Web开发变得更加容易和高效。
Iris 框架
lris是一个快速,简单但功能齐全的和非常有效的web框架。提供了一个优美的表现力和容易使用你的下一个网站或API的基础。
简单使用Gin
首先,第一步,下载并安装gin
go get -u github.com/gin-gonic/gin
第二步,引入包
import "github.com/gin-gonic/gin"
package main
import "github.com/gin-gonic/gin"
func main() {
// 创建一个服务
ginServer := gin.Default()
// 连接数据库的代码
// 访问地址,处理我们的请求
Request ResponseginServer.GET( relativePath:"/hello",func(context *gin.Context) {context.JSON( code: 200, gin.H{"msg":"hello,world"})
// 服务器端口
ginServer.Run( addr...: ":8082")
还可以添加网页的favicon
import "github.com/thinkerou/favicon"
ginServer.Use(favicon.New(path:"./favicon.ico"))
RESTful风格API
首先,介绍一下RESTful风格:
Restful是一种设计风格。对于我们Web开发人员来说。就是使用一个url地址表示一个唯一的资源。然后把原来的请求参数加入到请求资源地址中。然后原来请求的增,删,改,查操作。改为使用HTTP协议中请求方式GET、POST、PUT、DELETE表示。把请求参数加入到请求的资源地址中,原来的增,删,改,查。使用HTTP请求方式,POST、DELETE、PUT、GET分别一一对应。
使用Gin 编写RESTful风格的API是十分简单的,只需要在服务变量后面加.get .post .put .delete即可
Gin也可以很方便地渲染前端
首先,创建templates文件夹,下面放静态页面,比如index.html
之后,在main.go文件中加载静态页面
// 加载静态页面
ginServer.LoadHTMLGLob( pattern:"templates/*")
之后,写一个get方法返回静态页面
// 响应一个页面给前端
ginServer.GET( relativePath:"/index",func(context *gin.Context)
{//context.JSON() json 数据
context.HTML(http.StatusOK, name:"index.html", gin.H{
"msg":"这是go后台传递来的数据”})
})
在templates/index.html里也可以接收到后端传来的数据
获取的数据为:{{.msg}}
html也可以加载css和js,首先新建static目录,下面放css目录和js目录,里面分别放具体的文件,之后在index.html里编写
<link rel="stylesheet" href="/static/css/style.css">
<script src="/static/js/common.js"></script>
在main.go文件中要加载
// 加载资源文件
ginServer.Static( relativePath:"/static",root:"./static")
因此,go语言可以给前端返回页面,可以做全栈开发,也可以只写后端,做前后端分离项目。
接受前端传来的参数
有两种方式,一种是使用url?userid=1&username=xxx 另一种方式是使用restful风格 url/:userid/:username 代码分别如下
// usl?userid=xxx&username=kuangshen
ginServer.GET( relativePath:"/user/info",func(context *gin.Context) {
userid := context.Query("userid")
username := context.Query( "username")
context.JSON(http.Status0K, gin.H{
"userid".userid.
"username": username
})
})
// /user/info/1/kuangshen
ginServer.GET( relativePath:"/user/info/:userid/:username", func(context *qin.Context){
userid := context.Param("userid")
username := context.Param( "username")
context.JSON(http.Status0K,gin.H{"userid".userid,
username": username,})
})
后端还可以接受来自前端的json格式的数据
// 前端给后端传递 jsonginServer.POST( relativePath:"/json",func(context *gin.Context) {
// request .body
// []byte类型
data, - := context.GetRawData()
var m map[string]interfacel{}
// 包装为json数据
json.Unmarshal(data, &m)
context.JSON(http.Status0K,m)
})
前端还可以传递表单,在前端页面编写:
<form action="user/add" method="post">
<p>username:<input type="text"name="username"> </p>
<p>password:<input type="text" name="password"> </p>
<button type="submit"> 提交 </button>
</form>
在后端页面编写:
ginServer.POST( relativePath:"/user/add",func(context *gin.Context){
username := context.PostForm("username")
password := context.PostForm( key:"password")
context.JSON(http.Status0K,gin.H{
"msg" : "ok",
"username": username,
"password": password,
})
})
这样子后端就能接受表单数据了
路由处理
gin也可以处理路由,可以进行路由重定向。
// 重定向 301
ginServer.GET( relativePath:"/test",func(context *gin.Context){
context.Redirect(http.StatusMovedPermanently, location: "https://www.baidu.com")
})
// 404 NRoute
ginServer.NoRoute(func(context *gin.Context) {context.HTML(http.StatusNotFound, "404.html")
})
还可以使用路由组处理路由
// 路由组 /user
userGroup := ginServer.Group( relativePath:"/user"){
userGroup.GET( relativePath:"/add")
userGroup.GET( relativePath: "/ogin")
userGroup .GET( relativePath: "/ogout")
}
Go中间件 拦截器
//注册中间件
ginServer.User(myHandler())
// 自定义Go中间件 拦截器
func myHandler() (gin.HanderFunc) {
return func(context *gin.Context) {
//通过自定义的中间件,设置的值,在后续处理只要调用了这个中间件的都可以拿到这里的参数
context.Set( "usersession","userid-1")
contex.Next() // 放行
context.Abort() // 阻止
}
}
可以对之前的代码应用这个在中间件,改造后代码如下:
// usl?userid=xxx&username=kuangshen
ginServer.GET( relativePath:"/user/info",myHandler(),func(context *gin.Context) {
//取出中间件的值
usersession:=context.MustGet("userSession").(string)
log.Println("================>",usersession)
userid := context.Query("userid")
username := context.Query( "username")
context.JSON(http.Status0K, gin.H{
"userid".userid,
"username": username,
})
})