Gin是一个web框架
获取Gin
提前设置个全球代理
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.io,direct
go get -u github.com/gin-goinc/gin
导入gin
IDEA中环境配置一下
第一个hello world
package main
import "github.com/gin-gonic/gin"
func main() {
ginServer := gin.Default()
ginServer.GET("/hello", func(context *gin.Context) {
context.JSON(200, gin.H{"msg": "hello world"})
})
ginServer.Run(":8899")
}
设置favicon
ginServer.Use(favicon.New(“./favicon.ico”))
前端页面模板
package main
import "github.com/gin-gonic/gin"
import "github.com/thinkerou/favicon"
func main() {
ginServer := gin.Default()
ginServer.Use(favicon.New("./favicon.ico"))
//加载静态页面
ginServer.LoadHTMLGlob("tmplate/*")
//ginServer.LoadHTMLFiles("tmplate/*")
ginServer.GET("/hello", func(context *gin.Context) {
context.JSON(200, gin.H{"msg": "hello world"})
})
ginServer.POST("/post", func(context *gin.Context) {
context.JSON(200, gin.H{"msg": "post"})
})
//响应一个页面
ginServer.GET("/", func(context *gin.Context) {
context.HTML(200, "index.html", gin.H{
"msg": "动态数据传输",
})
})
ginServer.Run(":8899")
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>yes</title>
</head>
<body>
<h1>hello boys</h1>
{{.msg}}
</body>
</html>
接收参数
get
ginServer.GET("/info", func(context *gin.Context) {
username := context.Query("username")
context.JSON(http.StatusOK, gin.H{
"username": username,
})
})
POST
ginServer.POST("/login", func(context *gin.Context) {
username := context.PostForm("username")
password := context.PostForm("password")
context.String(200, username)
context.String(200, password)
context.String(200, "welcome"+username)
})
路由
重定向
ginServer.GET("/redirect", func(context *gin.Context) {
context.Redirect(301, "http://127.0.0.1/login")
})
404
ginServer.NoRoute(func(context *gin.Context) {
context.HTML(404, "404.html", nil)
})
路由组
//路由组
userGroup := ginServer.Group("/user")
{
userGroup.GET("/info")
userGroup.GET("/login")
}
中间件
定义中间件
//自定义一个中间件
func Handler() gin.HandlerFunc {
return func(context *gin.Context) {
// 自动中间件,设置的值,在后续处理只要调用了中间件都可以拿到这里的参数
context.Set("usersession", "userid-1")
if true{
context.Next()//放行
}
context.Abort()//阻止
}
}
注册中间件
//注册中间件
ginServer.Use(Handler())
使用中间件
ginServer.GET("/hello",Handler(), func(context *gin.Context) {
context.JSON(200, gin.H{"msg": "hello world"})
})