github.com/orangebees/go-oneutils@v0.0.10/Response/func.go (about) 1 package Response 2 3 import ( 4 "encoding/json" 5 "github.com/orangebees/go-oneutils/ExtErr" 6 "github.com/orangebees/go-oneutils/Fetch" 7 "strings" 8 ) 9 10 type EasyJsonResponse struct { 11 Code int 12 Msg string 13 Data Fetch.EasyJsonSerialization 14 } 15 type Response struct { 16 Code int `json:"code"` 17 Msg string `json:"msg,omitempty"` 18 Data any `json:"data,omitempty"` 19 } 20 21 func (r *Response) IsSuccess() bool { 22 if r.Code != 0 { 23 return false 24 } 25 return true 26 } 27 func (r *EasyJsonResponse) IsSuccess() bool { 28 if r.Code != 0 { 29 return false 30 } 31 return true 32 } 33 34 // 0-9 为保留状态码 35 const ( 36 // SuccessCode 成功 相当于200 37 SuccessCode = iota 38 // FailCode 失败/通用错误中止 相当于500 39 FailCode 40 // ParameterErrorCode 参数错误 相当于400 41 ParameterErrorCode 42 // AccessAbortedCode 访问中止 相当于403 43 AccessAbortedCode 44 // AccessAbortedCallbackCode 访问中止回调 相当于403+302 跳转到黑名单,登陆失败/失效的提示,工作页面 登录时不建议使用 45 AccessAbortedCallbackCode 46 ) 47 48 const ( 49 DefaultSuccessResponse = `{"code":0,"msg":"ok"}` 50 DefaultFailResponse = `{"code":1,"msg":"Unknown error"}` 51 DefaultSerializationFailResponse = `{"code":1,"msg":"Serialization error"}` 52 DefaultParameterErrorResponse = `{"code":2,"msg":"Error or missing parameter"}` 53 DefaultAccessAbortedResponse = `{"code":3,"msg":"AccessFail"}` 54 ) 55 56 // IsSuccess 快速判断是否成功,仅用于此包内生成的响应字符串 57 func IsSuccess(string2 string) bool { 58 if len(string2) <= 9 { 59 return false 60 } 61 if strings.HasPrefix(string2, DefaultSuccessResponse[:9]) { 62 return true 63 } 64 return false 65 } 66 67 // EasyJsonSuccess 成功响应,data建议传指针类型的值 68 func EasyJsonSuccess(data Fetch.EasyJsonSerialization) string { 69 if data == nil { 70 return DefaultSuccessResponse 71 } 72 73 marshal, err := data.MarshalJSON() 74 if err != nil { 75 return DefaultSerializationFailResponse 76 } 77 return `{"code":0,"msg":"ok","data":` + string(marshal) + "}" 78 } 79 80 // Success 成功响应 81 func Success(data any) string { 82 if data == nil { 83 return DefaultSuccessResponse 84 } 85 marshal, err := json.Marshal(Response{ 86 Data: data, 87 }) 88 if err != nil { 89 return DefaultSerializationFailResponse 90 } 91 return string(marshal) 92 } 93 94 // Fail 失败响应 95 func Fail(err ExtErr.Err) string { 96 if err == nil { 97 return DefaultFailResponse 98 } 99 estr := err.Error() 100 estrlen := len(estr) 101 //删除特殊字符 102 tmpbytes := make([]byte, estrlen) 103 for i := 0; i < estrlen; i++ { 104 t := estr[i] 105 //跳过不可见非法字符 106 if t == '\n' || t == '\t' { 107 continue 108 } 109 //可见非法字符转换 110 if t == '"' { 111 tmpbytes = append(tmpbytes, '\\') 112 } 113 tmpbytes = append(tmpbytes, t) 114 } 115 return `{"code":` + err.ErrorCodeString() + `,"msg":"` + string(tmpbytes) + `"}` 116 }