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

56 lines
1015 B

  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"`
  13. Msg string `json:"msg"`
  14. Status bool `json:"status"`
  15. }
  16. func (j *Json) String() string {
  17. s, _ := j.ToString()
  18. return s
  19. }
  20. func (j *Json) ToString() (str string, err error) {
  21. var b []byte
  22. b, err = json.Marshal(j)
  23. return bytes.NewBuffer(b).String(), err
  24. }
  25. func NewJsonByDefaultSuccess(data ...interface{}) *Json {
  26. return NewJson(true, 0, JsonMsgDefaultOk, data...)
  27. }
  28. func NewJsonByDefaultFailed(data ...interface{}) *Json {
  29. return NewJson(false, 1, JsonMsgDefaultFailed, data...)
  30. }
  31. func NewJson(status bool, code int, msg string, data ...interface{}) *Json {
  32. if len(data) > 0 {
  33. return &Json{
  34. Code: code,
  35. Data: data[0],
  36. Msg: msg,
  37. Status: status,
  38. }
  39. } else {
  40. return &Json{
  41. Code: code,
  42. Data: nil,
  43. Msg: msg,
  44. Status: status,
  45. }
  46. }
  47. }