84 lines
1.5 KiB
Go
84 lines
1.5 KiB
Go
package response
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
)
|
|
|
|
const (
|
|
JsonMsgDefaultOk = "ok"
|
|
JsonMsgDefaultFailed = "unknown error"
|
|
)
|
|
|
|
type Json struct {
|
|
Code int `json:"code"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
Msg string `json:"msg"`
|
|
Status bool `json:"status"`
|
|
}
|
|
|
|
func (j *Json) GetDefaultSuccessCode() int {
|
|
return 0
|
|
}
|
|
|
|
func (j *Json) GetDefaultFailedCode() int {
|
|
return 10086
|
|
}
|
|
|
|
func (j *Json) SetCode(code int) {
|
|
j.Code = code
|
|
}
|
|
|
|
func (j *Json) SetMessage(msg string) {
|
|
j.Msg = msg
|
|
}
|
|
|
|
func (j *Json) SetData(data interface{}) {
|
|
j.Data = data
|
|
}
|
|
|
|
func (j *Json) SetStatus(status bool) {
|
|
j.Status = status
|
|
}
|
|
|
|
func (j *Json) String() string {
|
|
s, _ := j.ToString()
|
|
return s
|
|
}
|
|
|
|
func (j *Json) ToString() (str string, err error) {
|
|
var b []byte
|
|
b, err = json.Marshal(j)
|
|
return bytes.NewBuffer(b).String(), err
|
|
}
|
|
|
|
func NewJsonByDefaultSuccess(data ...interface{}) JsonInterface {
|
|
return NewJson(true, 0, JsonMsgDefaultOk, data...)
|
|
}
|
|
|
|
func NewJsonByDefaultFailed(data ...interface{}) JsonInterface {
|
|
return NewJson(false, 1, JsonMsgDefaultFailed, data...)
|
|
}
|
|
|
|
func NewJonsByFailed(code int, msg string) JsonInterface {
|
|
return NewJson(false, code, msg)
|
|
}
|
|
|
|
func NewJson(status bool, code int, msg string, data ...interface{}) JsonInterface {
|
|
if len(data) > 0 {
|
|
return &Json{
|
|
Code: code,
|
|
Data: data[0],
|
|
Msg: msg,
|
|
Status: status,
|
|
}
|
|
} else {
|
|
return &Json{
|
|
Code: code,
|
|
Data: nil,
|
|
Msg: msg,
|
|
Status: status,
|
|
}
|
|
}
|
|
}
|