You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1008 B

  1. package response
  2. import (
  3. "net/http"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. )
  7. // JsonRes 数据返回通用JSON数据结构
  8. type JsonRes struct {
  9. Code int `json:"code"` // 错误码((0:成功, 1:失败, >1:错误码))
  10. Message string `json:"msg"` // 提示信息
  11. Data interface{} `json:"data"` // 返回数据(业务接口定义具体数据结构)
  12. }
  13. // Json 返回标准JSON数据。
  14. func Json(r *ghttp.Request, code int, message string, data ...interface{}) {
  15. var responseData interface{}
  16. if len(data) > 0 {
  17. responseData = data[0]
  18. } else {
  19. responseData = g.Map{}
  20. }
  21. r.Response.WriteJson(JsonRes{
  22. Code: code,
  23. Message: message,
  24. Data: responseData,
  25. })
  26. }
  27. // JsonExit 返回标准JSON数据并退出当前HTTP执行函数。
  28. func JsonExit(r *ghttp.Request, code int, message string, data ...interface{}) {
  29. if code == http.StatusBadRequest {
  30. g.Log().Error(r.Context(), code, message)
  31. }
  32. Json(r, code, message, data...)
  33. r.Exit()
  34. }