carv api logic
This commit is contained in:
@@ -3,12 +3,15 @@ package errs
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"github.com/zeromicro/go-zero/rest"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const JsonContentType = "application/json; charset=utf-8"
|
||||
|
||||
func init() {
|
||||
httpx.SetErrorHandlerCtx(ErrorHandleCtx)
|
||||
httpx.SetErrorHandler(ErrorHandle)
|
||||
@@ -72,3 +75,24 @@ func ErrorHandleCtx(ctx context.Context, err error) (int, any) {
|
||||
}
|
||||
return http.StatusOK, body
|
||||
}
|
||||
|
||||
func WriteHttpResponse(ctx context.Context, w http.ResponseWriter, v any) {
|
||||
w.Header().Set(httpx.ContentType, JsonContentType)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
body, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
logx.WithContext(ctx).Errorw("error marshal response", logx.Field("error", err), logx.Field("value", v))
|
||||
return
|
||||
}
|
||||
|
||||
if n, err := w.Write(body); err != nil {
|
||||
// http.ErrHandlerTimeout has been handled by http.TimeoutHandler,
|
||||
// so it's ignored here.
|
||||
if !errors.Is(err, http.ErrHandlerTimeout) {
|
||||
logx.WithContext(ctx).Errorw("write response failed, error", logx.Field("error", err), logx.Field("value", v))
|
||||
}
|
||||
} else if n < len(body) {
|
||||
logx.WithContext(ctx).Errorf("actual bytes: %d, written bytes: %d", len(body), n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,4 +27,5 @@ const (
|
||||
ErrTaskConfNotSet Reason = 20006 // 任务配置未设置
|
||||
ErrUserNotFound Reason = 20007 // 用户不存在
|
||||
ErrNftNotBelongToUser Reason = 20008 // NFT不属于用户
|
||||
ErrInvalidApiKey Reason = 20009 // 无效的api key
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user