Files
ocean/gateway/internal/handler/createcategoryhandler.go

51 lines
1.2 KiB
Go

package handler
import (
"net/http"
"godemo/gateway/internal/logic"
"godemo/gateway/internal/svc"
"godemo/gateway/internal/types"
"github.com/zeromicro/go-zero/rest/httpx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func createCategoryHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CreateCategoryReq
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := logic.NewCreateCategoryLogic(r.Context(), svcCtx)
resp, err := l.CreateCategory(&req)
if err != nil {
if s, ok := status.FromError(err); ok {
// 判断 gRPC 错误码,并自定义 HTTP 返回
var code int
switch s.Code() {
case codes.NotFound:
code = http.StatusNotFound
case codes.InvalidArgument:
code = http.StatusBadRequest
default:
code = http.StatusInternalServerError
}
// 自定义 JSON 错误格式
httpx.WriteJson(w, code, map[string]interface{}{
"code": code,
"message": s.Message(),
})
} else {
httpx.ErrorCtx(r.Context(), w, err)
}
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}