使用Gin框架进行Web开发时,你可能希望在HTTP响应中格式化输出数据。
封装格式化函数
package controllers
type OutData struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
func SetOut(code int, data interface{}) *OutData {
return &OutData{Code: code, Message: setCodeMessage(code), Data: data}
}
func setCodeMessage(code int) string {
var message = ""
switch code {
case 200:
message = "数据加载成功"
case 400:
message = "数据加载失败"
case 404:
message = "接口不存在"
case 401:
message = "权限不足"
case 500:
message = "服务器内部错误"
default:
message = ""
}
return message
}
路由中引用
c.JSON(http.StatusNotFound, controllers.SetOut(404, nil))
c.JSON(http.StatusOK, controllers.SetOut(200, "pong"))
user := &User{Id: 1, Name: "小明", Habits: []string{"看书", "看电影"}}
c.JSON(http.StatusOK, SetOut(200, user))
c.JSON(http.StatusOK, SetOut(200, "Login successful"))
c.JSON(http.StatusUnauthorized, controllers.SetOut(401, "Unauthorized"))
返回 JSON
r.GET("/user", func(c *gin.Context) {
user := map[string]interface{}{
"id": 1,
"name": "John Doe",
}
c.JSON(200, gin.H{"data": user})
})
返回 HTML 模板
// 加载模板文件
r.LoadHTMLGlob("templates/*")
r.GET("/home", func(c *gin.Context) {
c.HTML(200, "index.html", gin.H{
"title": "Home Page",
"content": "Welcome to Gin!",
})
})
文件下载
r.GET("/download", func(c *gin.Context) {
filePath := "/path/to/file.zip"
c.Header("Content-Disposition", "attachment; filename=file.zip")
c.File(filePath)
})
静态文件服务
// 映射 /static 到 ./assets 目录
r.Static("/static", "./assets")