统一初始beego mvc 的方法
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.

84 lines
1.5 KiB

  1. package response
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. )
  6. const (
  7. JsonMsgDefaultOk = "ok"
  8. JsonMsgDefaultFailed = "unknown error"
  9. )
  10. type Json struct {
  11. Code int `json:"code"`
  12. Data interface{} `json:"data,omitempty"`
  13. Msg string `json:"msg"`
  14. Status bool `json:"status"`
  15. }
  16. func (j *Json) GetDefaultSuccessCode() int {
  17. return 0
  18. }
  19. func (j *Json) GetDefaultFailedCode() int {
  20. return 10086
  21. }
  22. func (j *Json) SetCode(code int) {
  23. j.Code = code
  24. }
  25. func (j *Json) SetMessage(msg string) {
  26. j.Msg = msg
  27. }
  28. func (j *Json) SetData(data interface{}) {
  29. j.Data = data
  30. }
  31. func (j *Json) SetStatus(status bool) {
  32. j.Status = status
  33. }
  34. func (j *Json) String() string {
  35. s, _ := j.ToString()
  36. return s
  37. }
  38. func (j *Json) ToString() (str string, err error) {
  39. var b []byte
  40. b, err = json.Marshal(j)
  41. return bytes.NewBuffer(b).String(), err
  42. }
  43. func NewJsonByDefaultSuccess(data ...interface{}) JsonInterface {
  44. return NewJson(true, 0, JsonMsgDefaultOk, data...)
  45. }
  46. func NewJsonByDefaultFailed(data ...interface{}) JsonInterface {
  47. return NewJson(false, 1, JsonMsgDefaultFailed, data...)
  48. }
  49. func NewJonsByFailed(code int, msg string) JsonInterface {
  50. return NewJson(false, code, msg)
  51. }
  52. func NewJson(status bool, code int, msg string, data ...interface{}) JsonInterface {
  53. if len(data) > 0 {
  54. return &Json{
  55. Code: code,
  56. Data: data[0],
  57. Msg: msg,
  58. Status: status,
  59. }
  60. } else {
  61. return &Json{
  62. Code: code,
  63. Data: nil,
  64. Msg: msg,
  65. Status: status,
  66. }
  67. }
  68. }