package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/thinkerou/favicon"
)
//自定义go中间件即拦截器
//给所有请求使用 则不不写在下列方法里,写了则拦截指定方法的请求
func myHandler() (gin.HandlerFunc) {
//通过自定义的中间件,设置的值,在后续处理只要调用了这个中间件的都可以拿到这里的参数
return func(context *gin.Context) {
context.Set("usersession","userid-1")
//if ...
context.Next() //放行
context.Abort() //阻止
}
}
func main() {
//创建一个服务
ginServer := gin.Default()
ginServer.Use(favicon.New("./favicon.ico"))
//加载静态页面
ginServer.LoadHTMLGlob("templates/*")
//加载资源目录
ginServer.Static("/static","./static")
//Gin Restful
ginServer.GET("/hello",myHandler(),func(Context *gin.Context) {
//取出中间件中的值
usersession := Context.MustGet("userSession").(string) //空接口转换为string
log.Println("------->",usersession)
Context.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.GET("/index",func(Context *gin.Context) {
Context.HTML(http.StatusOK,"index.html",gin.H{
"msg":"这是go后台传递来的数据",
})
//接收前端传递过来的参数
//info?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,
// })
// })
//info/1/kaungshen
ginServer.GET("/user/info/:userid/:username",func(context *gin.Context) {
userid := context.Param("userid")
username := context.Param("username")
context.JSON(200,gin.H{
"userid": userid,
"username": username,
})
})
//掌握技术后面的应用- 掌握基础知识,加以了解web知识
// 前端给后端传递 json
ginServer.POST("/json",func(context *gin.Context) {
//request.body
//[]body 返回的是切片
data,_ := context.GetRawData()
var m map[string]interface{}
//包装为json数据 []byte
_ = json.Unmarshal(data,&m)
context.JSON(200,m)
})
//支持表单
ginServer.POST("/user/add",func(context *gin.Context) {
username := context.PostForm("username")
password := context.PostForm("password")
context.JSON(200,gin.H{
"msg":"ok",
"username":username,
"password":password,
})
})
//路由
ginServer.GET("/test",func(context *gin.Context) {
//重定向
context.Redirect(301,"http://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.POST("/login")
userGroup.POST("/logout")
}
orderGroup := ginServer.Group("order")
{
orderGroup.GET("/add")
orderGroup.DELETE("/delete")
}
})
//服务器端口
ginServer.Run(":8082")
}