4_多数据格式返回请求结果.md

多数据格式返回请求结果

来源:https://www.qfgolang.com/?special=ginkuangjia&pid=2927

gin框架中,支持返回多种请求数据格式。

[]byte

...
engine := gin.Default()
engine.GET("/hello", func(context *gin.Context) {
        fullPath := "请求路径:" + context.FullPath()
        fmt.Println(fullPath)
        context.Writer.Write([]byte(fullPath))
})
engine.Run()
...

​ 使用context.Writer.Write向客户端写入返回数据。Writer是gin框架中封装的一个ResponseWriter接口类型。

string

WriteString方法返回数据。

context.Writer.WriteString(fullPath)

json

​ gin框架中的context包含的JSON方法可以将结构体类型的数据转换成JSON格式的结构化数据,然后返回给客户端。

map类型

context.JSON(200, map[string]interface{}{
        "code":    1,
        "message": "OK",
        "data":    fullPath,
    })

结构体类型

//通用请求返回结构体定义
type Response struct {
    Code    int         json:"code"
    Message string      json:"msg"
    Data    interface{} json:"data"
}

engine.GET("/jsonstruct", func(context *gin.Context) {
    fullPath := "请求路径:" + context.FullPath()
    fmt.Println(fullPath)
    resp := Response{Code: 1, Message: "Ok", Data: fullPath}
    context.JSON(200, &resp)
})

HTML模板

gin框架还支持返回HTML格式的数据。

...
engine := gin.Default()
//设置html的目录
engine.LoadHTMLGlob("./html/*")
engine.GET("/hellohtml", func(context *gin.Context) {
    fullPath := "请求路径:" + context.FullPath()

    context.HTML(http.StatusOK, "index.html", gin.H{
        "title":    "Gin教程",
        "fullpath": fullPath,
    })
})
engine.Run(":9000")
...

加载静态资源文件

engine.Static("/img", "./img")

在项目开发时,一些静态的资源文件如html、js、css等可以通过静态资源文件设置的方式来进行设置。

重定向

http重定向

r.GET("/test", func(c *gin.Context) {
	c.Redirect(http.StatusMovedPermanently, "http://www.sogo.com/")
})

路由重定向

r.GET("/test", func(c *gin.Context) {
    // 指定重定向的URL
    c.Request.URL.Path = "/test2"
    r.HandleContext(c)
})
r.GET("/test2", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"hello": "world"})
})
原文地址:https://www.cnblogs.com/nsfoxer/p/14451507.html