package main
import (
"encoding/json"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
import "github.com/thinkerou/favicon"
//自定义GO中间件 拦截器
func myHandler() (gin.HandlerFunc) {
return func(c *gin.Context) {
//通过自定义的中间件,设置的值,在后续处理只要调用了这个中间件的都可以拿到这里的参数
c.Set("usersession","userid-1")
c.Next() //放行
c.Abort() //阻止
}
}
func main() {
// 创建一个服务
ginServer := gin.Default()
ginServer.Use(favicon.New("./favicon.ico"))
//加载静态页面
ginServer.LoadHTMLGlob("templates/*") //加载所有
//ginServer.LoadHTMLFiles("templates/index.html") //加载一个单独的页面
//加载资源文件
ginServer.Static("/static","./static")
//响应一个页面给前端
ginServer.GET("/index", func(c *gin.Context) {
//HTML
c.HTML(http.StatusOK,"index.html",gin.H{
"msg":"data",
}) //返回json数据
})
//接收前端传递过来的参数
//usl?userid=xxx&username=lf
ginServer.GET("/user/info",myHandler(), func(c *gin.Context) {
//取出中间件中的值
usersession := c.MustGet("usersesssion").(string)
log.Println("===========================",usersession)
userid := c.Query("userid")
username := c.Query("username")
c.JSON(http.StatusOK,gin.H{
"userid":userid,
"username":username,
})
})
// /user/info/1/kuangshen
ginServer.GET("/user/info/:userid/:username", func(c *gin.Context) {
userid := c.Param("userid")
username := c.Param("username")
c.JSON(http.StatusOK,gin.H{
"userid":userid,
"username":username,
})
})
//掌握技术后面的应用 - 掌握基础知识,加以了解web开发
//前端给后端传递 json
ginServer.POST("/json", func(c *gin.Context) {
// request.body
data,_ := c.GetRawData()
var m map[string]interface{}
_ = json.Unmarshal(data,&m)
c.JSON(http.StatusOK,m)
})
//支持函数式编程
//前端表单提交一个数据后端接收
ginServer.POST("/user/add", func(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
c.JSON(http.StatusOK,gin.H{
"msg":"ok",
"username":username,
"password":password,
})
})
//路由301重定向
ginServer.GET("/test", func(c *gin.Context) {
c.Redirect(301,"https://www.duanwenxue.com")
})
//404 NoRoute
ginServer.NoRoute(func(c *gin.Context) {
c.HTML(http.StatusNotFound,"404.html",nil)
})
//路由组 /user/add
userGroup := ginServer.Group("/user")
{
userGroup.GET("/add")
userGroup.GET("/login")
userGroup.GET("/logout")
}
orderGroup := ginServer.Group("/order")
{
orderGroup.GET("/add")
orderGroup.DELETE("/delete" )
}
// 访问地址 处理请求 Request Response
ginServer.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{"msg": "hello world"})
})
ginServer.POST("/user", func(c *gin.Context) {
c.JSON(200,gin.H{"msg":"post,user"})
})
ginServer.PUT("/user")
ginServer.DELETE("/user")
ginServer.Run(":8888")
}
GO语言的Gin框架
最新推荐文章于 2024-03-25 21:19:36 发布