You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Open-IM-Server/pkg/apiresp/resp.go

59 lines
1.2 KiB

2 years ago
package apiresp
2 years ago
import (
2 years ago
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
2 years ago
"reflect"
2 years ago
)
2 years ago
type ApiResponse struct {
2 years ago
ErrCode int `json:"errCode"`
ErrMsg string `json:"errMsg"`
ErrDlt string `json:"errDlt"`
2 years ago
Data any `json:"data,omitempty"`
2 years ago
}
func isAllFieldsPrivate(v any) bool {
2 years ago
typeOf := reflect.TypeOf(v)
2 years ago
if typeOf == nil {
return false
}
2 years ago
if typeOf.Kind() == reflect.Ptr {
typeOf = typeOf.Elem()
}
if typeOf.Kind() != reflect.Struct {
return false
}
num := typeOf.NumField()
for i := 0; i < num; i++ {
c := typeOf.Field(i).Name[0]
if c >= 'A' && c <= 'Z' {
2 years ago
return false
}
}
return true
}
2 years ago
func ApiSuccess(data any) *ApiResponse {
if isAllFieldsPrivate(data) {
2 years ago
return &ApiResponse{}
2 years ago
}
2 years ago
return &ApiResponse{
2 years ago
Data: data,
}
}
2 years ago
func ParseError(err error) *ApiResponse {
2 years ago
if err == nil {
return ApiSuccess(nil)
}
2 years ago
unwrap := errs.Unwrap(err)
if codeErr, ok := unwrap.(errs.CodeError); ok {
2 years ago
resp := ApiResponse{ErrCode: codeErr.Code(), ErrMsg: codeErr.Msg(), ErrDlt: codeErr.Detail()}
2 years ago
if resp.ErrDlt == "" {
resp.ErrDlt = err.Error()
}
return &resp
2 years ago
}
2 years ago
return &ApiResponse{ErrCode: errs.ServerInternalError, ErrMsg: err.Error()}
2 years ago
}