增加成功失败值自定义返回,修改错别字

This commit is contained in:
liangzy 2021-08-03 20:02:00 +08:00
parent 40aca1e117
commit 851e2bd23c
4 changed files with 36 additions and 13 deletions

View File

@ -7,7 +7,7 @@ import (
const (
JsonMsgDefaultOk = "ok"
JsonMsgDefaultFailed = "unknown"
JsonMsgDefaultFailed = "unknown error"
)
type Json struct {
@ -17,6 +17,14 @@ type Json struct {
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
}

View File

@ -5,5 +5,7 @@ type JsonInterface interface {
SetMessage(msg string)
SetData(data interface{})
SetStatus(status bool)
ToString() (str string, err error)
//
GetDefaultSuccessCode() int
GetDefaultFailedCode() int
}

View File

@ -12,15 +12,20 @@ type A struct {
Json
}
func (j *A) String() string {
s, _ := j.ToString()
return s
func (j *A) GetDefaultSuccessCode() int {
return 0
}
func (a *A) ToString() (str string, err error) {
var b []byte
b, err = json.Marshal(a)
return bytes.NewBuffer(b).String(), err
func (j *A) GetDefaultFailedCode() int {
return -1
}
func (j *A) String() string {
b, err := json.Marshal(j)
if err == nil {
return bytes.NewBuffer(b).String()
}
return ""
}
func (a *A) SetCode(code int) {
@ -33,5 +38,5 @@ func TestNewJsonByDefaultSuccess(t *testing.T) {
func TestName(t *testing.T) {
resp := JsonResponseGenerator{&A{Code: 232}}
fmt.Println(fmt.Sprintf("%+v", resp.NewJonsByFailed(123232, "hahah")))
fmt.Println(fmt.Sprintf("%+v", resp.NewJsonByDefaultFailed()))
}

View File

@ -7,17 +7,25 @@ type JsonResponseGenerator struct {
}
func (j JsonResponseGenerator) NewJsonByDefaultSuccess(data ...interface{}) JsonInterface {
return j.NewJson(true, 0, JsonMsgDefaultOk, data...)
ptr := j.NewJson(true, 0, JsonMsgDefaultOk, data...)
ptr.SetCode(ptr.GetDefaultSuccessCode())
return ptr
}
func (j JsonResponseGenerator) NewJsonByDefaultFailed(data ...interface{}) JsonInterface {
return j.NewJson(false, 1, JsonMsgDefaultFailed, data...)
ptr := j.NewJson(false, 1, JsonMsgDefaultFailed, data...)
ptr.SetCode(ptr.GetDefaultFailedCode())
return ptr
}
func (j JsonResponseGenerator) NewJonsByFailed(code int, msg string) JsonInterface {
func (j JsonResponseGenerator) NewJsonByFailed(code int, msg string) JsonInterface {
return j.NewJson(false, code, msg)
}
func (j JsonResponseGenerator) NewJsonByFailedWithData(code int, msg string, data interface{}) JsonInterface {
return j.NewJson(false, code, msg, data)
}
func (j JsonResponseGenerator) NewJson(status bool, code int, msg string, data ...interface{}) JsonInterface {
jPtr := reflect.New(reflect.TypeOf(j.Interface).Elem())
if b, ok := jPtr.Interface().(JsonInterface); ok {