统一初始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.

76 lines
1.3 KiB

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