mirror of
https://github.com/openimsdk/open-im-server.git
synced 2026-05-12 21:16:00 +08:00
pkg
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
package apiresp
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func GinError(c *gin.Context, err error) {
|
||||
if err == nil {
|
||||
GinSuccess(c, nil)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, apiError(err))
|
||||
}
|
||||
|
||||
func GinSuccess(c *gin.Context, data any) {
|
||||
c.JSON(http.StatusOK, apiSuccess(data))
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package apiresp
|
||||
|
||||
import (
|
||||
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type apiResponse struct {
|
||||
ErrCode int `json:"errCode"`
|
||||
ErrMsg string `json:"errMsg"`
|
||||
ErrDlt string `json:"errDlt"`
|
||||
Data any `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func isAllFieldsPrivate(v any) bool {
|
||||
typeOf := reflect.TypeOf(v)
|
||||
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' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func apiSuccess(data any) *apiResponse {
|
||||
if isAllFieldsPrivate(data) {
|
||||
return &apiResponse{}
|
||||
}
|
||||
return &apiResponse{
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func apiError(err error) *apiResponse {
|
||||
unwrap := errs.Unwrap(err)
|
||||
if codeErr, ok := unwrap.(errs.CodeError); ok {
|
||||
return &apiResponse{ErrCode: codeErr.Code(), ErrMsg: codeErr.Msg(), ErrDlt: codeErr.Detail()}
|
||||
}
|
||||
return &apiResponse{ErrCode: errs.ServerInternalError, ErrMsg: err.Error()}
|
||||
}
|
||||
Reference in New Issue
Block a user