carv api logic

This commit is contained in:
lianghuanjie
2025-01-08 17:53:43 +08:00
parent 5c4862fd70
commit 5d2a0a8b5d
14 changed files with 252 additions and 62 deletions

View File

@@ -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)
}
}

View File

@@ -27,4 +27,5 @@ const (
ErrTaskConfNotSet Reason = 20006 // 任务配置未设置
ErrUserNotFound Reason = 20007 // 用户不存在
ErrNftNotBelongToUser Reason = 20008 // NFT不属于用户
ErrInvalidApiKey Reason = 20009 // 无效的api key
)