gocron/modules/utils/json.go

65 lines
1.4 KiB
Go
Raw Normal View History

2017-04-01 09:04:40 +00:00
package utils
2017-04-03 07:27:19 +00:00
import (
"encoding/json"
2017-04-07 01:22:00 +00:00
"github.com/ouqiang/gocron/modules/logger"
2017-04-03 07:27:19 +00:00
)
2017-04-01 09:04:40 +00:00
// json 格式输出
type response struct {
2017-04-02 02:38:49 +00:00
Code int `json:"code"` // 状态码 0:成功 非0:失败
Message string `json:"message"` // 信息
Data interface{} `json:"data"` // 数据
2017-04-01 09:04:40 +00:00
}
2017-04-13 09:35:59 +00:00
type JsonResponse struct{}
2017-04-01 09:04:40 +00:00
2017-04-02 02:19:52 +00:00
const ResponseSuccess = 0
const ResponseFailure = 1
2017-04-13 09:35:59 +00:00
const NotFound = 2
const AuthError = 3
const ServerError = 4
2017-04-01 09:04:40 +00:00
2017-04-13 09:35:59 +00:00
const SuccessContent = "操作成功"
const FailureContent = "操作失败"
2017-04-30 17:12:07 +00:00
func JsonResponseByErr(err error) string {
json := JsonResponse{}
if err != nil {
return json.CommonFailure(FailureContent, err)
}
return json.Success(SuccessContent, nil)
}
2017-04-13 09:35:59 +00:00
func (j *JsonResponse) Success(message string, data interface{}) string {
2017-04-02 02:38:49 +00:00
return j.response(ResponseSuccess, message, data)
2017-04-01 09:04:40 +00:00
}
2017-04-13 09:35:59 +00:00
func (j *JsonResponse) Failure(code int, message string) string {
2017-04-02 02:38:49 +00:00
return j.response(code, message, nil)
2017-04-01 09:04:40 +00:00
}
2017-04-13 09:35:59 +00:00
func (j *JsonResponse) CommonFailure(message string, err... error) string {
if len(err) > 0 {
logger.Warn(err)
}
return j.Failure(ResponseFailure, message)
}
func (j *JsonResponse) response(code int, message string, data interface{}) string {
2017-04-02 02:38:49 +00:00
resp := response{
Code: code,
Message: message,
Data: data,
}
result, err := json.Marshal(resp)
if err != nil {
2017-04-03 07:27:19 +00:00
logger.Error(err)
2017-04-02 02:38:49 +00:00
}
return string(result)
2017-04-01 09:04:40 +00:00
}