相关方法:

  1. func (r *Response) WriteJson(content interface{}) error
  2. func (r *Response) WriteJsonExit(content interface{}) error
  3. func (r *Response) WriteJsonP(content interface{}) error
  4. func (r *Response) WriteJsonPExit(content interface{}) error
  5. func (r *Response) WriteXml(content interface{}, rootTag ...string) error
  6. func (r *Response) WriteXmlExit(content interface{}, rootTag ...string) error

Response提供了对JSON/XML数据格式输出的原生支持,通过以下方法实现:

  1. WriteJson* 方法用于返回JSON数据格式,参数为任意类型,可以为stringmapstruct等等。返回的Content-Typeapplication/json
  2. WriteXml* 方法用于返回XML数据格式,参数为任意类型,可以为stringmapstruct等等。返回的Content-Typeapplication/xml

JSON数据格式支持的同时,同时也支持JSONP协议。

JSON

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.Group("/", func(group *ghttp.RouterGroup) {
  9. group.ALL("/json", func(r *ghttp.Request) {
  10. r.Response.WriteJson(g.Map{
  11. "id": 1,
  12. "name": "john",
  13. })
  14. })
  15. })
  16. s.SetPort(8199)
  17. s.Run()
  18. }

执行后,我们通过curl工具测试下:

  1. $ curl -i http://127.0.0.1:8199/json
  2. HTTP/1.1 200 OK
  3. Content-Type: application/json
  4. Server: GF HTTP Server
  5. Date: Sun, 05 Jan 2020 02:49:31 GMT
  6. Content-Length: 22
  7. {"id":1,"name":"john"}

JSONP

需要注意使用JSONP协议时必须通过Query方式提供callback参数。

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.Group("/", func(group *ghttp.RouterGroup) {
  9. group.ALL("/jsonp", func(r *ghttp.Request) {
  10. r.Response.WriteJsonP(g.Map{
  11. "id": 1,
  12. "name": "john",
  13. })
  14. })
  15. })
  16. s.SetPort(8199)
  17. s.Run()
  18. }

执行后,我们通过curl工具测试下:

  1. $ curl -i "http://127.0.0.1:8199/jsonp?callback=MyCallback"
  2. HTTP/1.1 200 OK
  3. Server: GF HTTP Server
  4. Date: Sun, 05 Jan 2020 02:50:42 GMT
  5. Content-Length: 34
  6. Content-Type: text/plain; charset=utf-8
  7. MyCallback({"id":1,"name":"john"})

XML

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.Group("/", func(group *ghttp.RouterGroup) {
  9. group.ALL("/xml", func(r *ghttp.Request) {
  10. r.Response.Write(`<?xml version="1.0" encoding="UTF-8"?>`)
  11. r.Response.WriteXml(g.Map{
  12. "id": 1,
  13. "name": "john",
  14. })
  15. })
  16. })
  17. s.SetPort(8199)
  18. s.Run()
  19. }

执行后,我们通过curl工具测试下:

  1. $ curl -i http://127.0.0.1:8199/xml
  2. HTTP/1.1 200 OK
  3. Content-Type: application/xml
  4. Server: GF HTTP Server
  5. Date: Sun, 05 Jan 2020 03:00:55 GMT
  6. Content-Length: 76
  7. <?xml version="1.0" encoding="UTF-8"?><doc><id>1</id><name>john</name></doc>