这是我参与「第五届青训营 」伴学笔记创作活动的第 4 天
Go -GoWeb开发之Gin框架
- Gin: Go语言编写的Web框架,以更好地性能实现类似Martini框架的API
- Beego: 开源的高性能 Go语言Web框架
- Iris: 全宇宙最快的Go语言Web框架,完备MVC支持,未来尽在掌握
Gin 安装使用
下载并安装gin:
go get -u github.com/gin-gonic/gin
注:需要配置代理地址:
go env -w GOPROXY=https://goproxy.cn,direct
一下代码可以启动一个8082端口的服务
import "github.com/gin-gonic/gin"
func main() {
// 创建一个服务
ginServer := gin.Default()
// 访问地址,处理我们的请求, Request Response
ginServer.GET("/hello", func(context *gin.Context) {
context.JSON(200, gin.H{"msg": "Hello world"})
})
// 服务器端口
ginServer.Run(":8082")
}
Restful API
以前写网站
get /user post /create_user post /update_user post /delete_user
RESTful API
响应一个页面回来
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// 创建一个服务
ginServer := gin.Default()
// 访问地址,处理我们的请求, Request Response
ginServer.GET("/hello", func(context *gin.Context) {
context.JSON(200, gin.H{"msg": "Hello world"})
})
//加载静态页面
ginServer.LoadHTMLGlob("templates/*")
// 加载资源文件
ginServer.Static("/static", "./static")
// 相应一个页面给前端
ginServer.GET("/index", func(context *gin.Context) {
context.HTML(http.StatusOK, "index.html", gin.H{
"msg": "go给你的数据",
})
})
// 服务器端口
ginServer.Run(":8082")
}
接收参数
// usl?userid=xxx&username=kuangshen
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,
})
})
// usl/info/1/kuangshen
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,
})
})
前端传递参数给后端
json解析
// 前端给后端传递 json
ginServer.POST("/json", func(context *gin.Context) {
//request.body
data, _ := context.GetRawData()
var m map[string]interface{}
_ = json.Unmarshal(data, &m)
context.JSON(http.StatusOK, m)
})
表单提交
// 表单提交
ginServer.POST("/user/add", func(context *gin.Context) {
username := context.PostForm("username")
password := context.PostForm("password")
context.JSON(http.StatusOK, gin.H{
"msg": username,
"p": password,
})
})
路由和路由组
// 路由
ginServer.GET("/test", func(context *gin.Context) {
// 重定向
context.Redirect(301, "https://www.baidu.com")
})
// 404 NoRoute
ginServer.NoRoute(func(context *gin.Context) {
context.HTML(http.StatusNotFound, "404.html", nil)
})
// 路由组
userGroup := ginServer.Group("/user"){
userGroup.GET("/add")
userGroup.GET("/login")
userGroup.GET("/logout")
}
order := ginServer.Group("/order"){
order.GET("/add")
order.DELETE("/delete")
}
中间件-拦截器
中间件可以用来做权限过滤、处理
// 自定义Go中间件 拦截器
func myHandler()(gin.HandlerFunc) {
return func(context *gin.Context) {
//通过自定义的中间件,设置的值,在后续处理只要调用这个中间件的都可以拿到这里的参数
context.Set("usersession","userid-1")
context.Next()//放行
context.Abort() //阻止
}
}