一. 响应数据
- 在gin中请求接口响应时,实际可以响应会html,text,plain,json和xml等
- 比如前面gin基础示例中,接口响应时可以使用:
- gin.Context.string(“数据”),表示响应一个字符串
- gin.Context.c.JSON(),设置响应有json
//响应一个字符串
c.String(http.StatusOK, "响应数据")
//响应一个json
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
- gin.H是⼀个强⼤的⼯具,有点像map,可以自定义响应的key,value等等
type H map[string]interface{}
- 也可以编写结构体,将指定结构体以json格式响应出去,示例:
//1.响应结构体
type Login struct {
User string `form:"username" json:"user" uri:"user" xml:"user"`
Password string `form:"password" json:"password" uri:"password"xml:"password"`
}
func JsonFunc(c *gin.Context) {
//1.创建接收参数对应的结构体变量
var login Login
//2.解析JSON
if err := c.Bind(&login); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
//3.响应json
c.JSON(http.StatusOK,login)
//或使用gin.H{}
//c.JSON(http.StatusOK,gin.H{"user": "ls", "Message": "hey", "Number": 123})
}
- 注意点: 响应的结构体不要忘记你打tag
- 另外还有响应xml,yaml,ProtoBuf等
//响应xml格式
router.GET("/someXML", func(c *gin.Context) {
c.XML(http.StatusOK, gin.H{"user": "ls", "message": "hey", "status":
http.StatusOK})
})
//响应YAML格式
router.GET("/someYAML", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
//响应ProtoBuf格式
router.GET("/someProtoBuf", func(c *gin.Context) {
reps := []int64{int64(1), int64(2)}
label := "test"
//protobuf的特定定义写在testdata / protoexample文件中
data := &protoexample.Test{
Label: &label,
Reps: reps,
}
//注意在响应中数据变为二进制数据
//将输出protoexample.test protobuf序列化数据
c.ProtoBuf(http.StatusOK, data)
})
二. c.Writer.Header().Set处理响应头
- c.Writer.Header().Set方法是一种设置响应头的方式,它可以接受两个字符串类型的参数,分别表示响应头的名称和值
func main() {
r := gin.Default() // 创建一个默认的gin引擎
// 注册一个GET路由
r.GET("/hello", func(c *gin.Context) {
// 设置响应头中的Content-Type为text/plain
c.Writer.Header().Set("Content-Type", "text/plain")
// 返回200状态码和"Hello, world!"字符串
c.String(200, "Hello, world!")
})
r.Run(":8080") // 启动服务器
}