Context响应,重定向,自定义函数,Abort

发布时间 2023-04-10 21:32:57作者: yangphp

前言:

Context 对象提供了很多内置的响应形式,JSONHTMLProtobuf MsgPackYaml String等。它会为每一种形式都单独定制一个渲染器。

ContextGin最重要的部分。它允许我们在中间件之间 传递变量,管理流程,验证请求的JSON 并 呈现JSON响应。

正文:

 

content响应字符串,json,及重定向

jsonp 解决跨域访问问题

 

c.JSONP(200, gin.H{
        "status": "success",
        "code":   800,
})

重定向 百度

c.Redirect(http.StatusFound, "https://www.baidu.com")

 

重定向到站内地址

c.Request.URL.Path = "/success"

router.HandleContext(c)

 

响应字符串,json,及重定向实例:

func main() {
    router := gin.Default()
    router.GET("index", func(c *gin.Context) {
        //响应文本
        //c.String(200, "hello  this is index ")

        //响应json
        /*c.JSON(200, gin.H{
            "status": "success",
            "code":   800,
        })*/

        //响应jsonp 解决跨域访问问题
        /*c.JSONP(200, gin.H{
            "status": "success",
            "code":   800,
        })*/

        //获取请求信息
        //c.String(http.StatusOK, c.Request.Method+"\n")
        //c.String(http.StatusOK, c.Request.RequestURI+"\n")
        //c.String(http.StatusOK, c.Request.RemoteAddr+"\n")

        //重定向 到 百度
        //c.Redirect(http.StatusFound, "https://www.baidu.com")

        //重定向到站内地址
        c.Request.URL.Path = "/success"
        router.HandleContext(c)

    })

    router.GET("success", func(c *gin.Context) {
        c.String(http.StatusOK, "login success")
    })

    router.Run()
}

content加载html

加载静态文件夹

router.Static("img", "static/image")

加载某个文件

router.StaticFile("/1.jpg", "static/image/1.jpg")

加载html文件

router.LoadHTMLGlob("view/*")

加载多层次文件夹下的html

router.LoadHTMLGlob("view/**/*")

加载html页面

c.HTML(http.StatusOK, "index.html", gin.H{

"title": "index.html ...",

"name":  "加载html模板",

})

 

html文件里面需要使用define

{{define "user/index.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>user {{.title}}</p>
<p>user {{.name}}</p>
</body>
</html>
{{end}}

html中自定义函数的使用

// 自定义函数
func Sum(a, b int) int {
    return a + b
}
main调用:
//设置全局自定义函数 要写在LoadHTMLGlob前面
    router.SetFuncMap(template.FuncMap{
        "sum": Sum,
    })

    //加载多层次文件夹下的html
    router.LoadHTMLGlob("view/**/*")

html中直接使用即可:
<p>{{sum 6 8}}</p>

修改模板分隔符:

router.Delims("{{","}}")  //修改渲染的分隔符

 

 

Abort() 阻止调用后面处理函数,当前函数后面代码还可以执行

c.Abort实例:

func loginMiddleware(c *gin.Context) {
   c.Redirect(http.StatusFound, "http://www.baidu.com") //跳转
   c.Abort() //不加这个abort后续代码还会执行
   return
   fmt.Println("hello login middleware")
}
func main() {
   router := gin.Default()
   router.GET("login", loginMiddleware, func(c *gin.Context) {
      fmt.Println("hello lgoin")
   })
   router.Run(":8000")
}

c.Set,c.Get实例

用来中间件向其他处理器传递数据

 

只在当前上下文环境生效,可以跨处理器传递数据

router.GET("login", func(c *gin.Context) {

   c.Set("status", "login")

   status, _ := c.Get("status")

 

   c.String(http.StatusOK, status.(string))

   c.String(http.StatusOK, c.GetString("status"))

})

//获取不到status,因为不是同一个请求

router.GET("logout", func(c *gin.Context) {

   c.String(http.StatusOK, c.GetString("status"))

})

cookie实例:

router.GET("/setcookie", setCookie)

router.GET("/getcookie", getCookie)

 

func setCookie(c *gin.Context) {

   c.SetCookie("user_name", "lampol", 0, "/", "localhost", true, true)

}

func getCookie(c *gin.Context) {

   name, _ := c.Cookie("name")

   c.String(http.StatusOK, name)

}

完结