feat: api result add code (#96)

This commit is contained in:
Li Wei authored and GitHub committed 2023-03-05 11:54:39 +08:00
1 parent dbbbc204fb
commit 2e639e0fef
9 files changed
+130 -89

No files matched your search

+34 -8
View File
@@ -1,21 +1,47 @@
package model
type RespCode int
const (
CodeOk RespCode = 0
// CodeError is the common error code
CodeError RespCode = 1000
// CodeUnauthorized is the error code for unauthorized
CodeUnauthorized RespCode = 1002
// CodeInvalidParam is the error code for invalid parameter
CodeInvalidParam RespCode = 1003
// CodeTaskNotFound is the error code for task not found
CodeTaskNotFound RespCode = 2001
)
type Result[T any] struct {
Msg string `json:"msg"`
Data T `json:"data"`
Code RespCode `json:"code"`
Msg string `json:"msg"`
Data T `json:"data"`
}
func NewResult[T any](msg string, data T) *Result[T] {
func NewOkResult[T any](data T) *Result[T] {
return &Result[T]{
Msg: msg,
Code: CodeOk,
Data: data,
}
}
func NewResultWithMsg(msg string) *Result[any] {
return NewResult[any](msg, nil)
func NewNilResult() *Result[any] {
return &Result[any]{
Code: CodeOk,
}
}
func NewResultWithData[T any](data T) *Result[T] {
return NewResult[T]("", data)
func NewErrorResult(msg string, code ...RespCode) *Result[any] {
// if code is not provided, the default code is CodeError
c := CodeError
if len(code) > 0 {
c = code[0]
}
return &Result[any]{
Code: c,
Msg: msg,
}
}