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

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

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.Group("/", func(group *ghttp.RouterGroup) {
  8. group.ALL("/json", func(r *ghttp.Request) {
  9. r.Response.WriteJson(g.Map{
  10. "id": 1,
  11. "name": "john",
  12. })
  13. })
  14. })
  15. s.Run()
  16. }

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

JSONP

  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. })
  13. })
  14. })
  15. s.SetPort(8199)
  16. s.Run()

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

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. }