66 lines
1.4 KiB
Go
66 lines
1.4 KiB
Go
package httputil
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"server/internal/model/common"
|
|
"server/internal/pkg/errs"
|
|
validatorI18 "server/internal/pkg/validator"
|
|
"strings"
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
)
|
|
|
|
func respondWithJSON(w http.ResponseWriter, code int, data any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(code)
|
|
if err := json.NewEncoder(w).Encode(data); err != nil {
|
|
slog.Error("respondWithJSON: failed to encode response", "error", err)
|
|
}
|
|
}
|
|
|
|
func Ok(w http.ResponseWriter, data ...any) {
|
|
resp := common.Response{
|
|
Message: "ok",
|
|
}
|
|
|
|
if len(data) > 0 && data[0] != nil {
|
|
resp.Data = data[0]
|
|
}
|
|
|
|
respondWithJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
func OkWithPage(w http.ResponseWriter, pageResp *common.PageResponse) {
|
|
pageResp.Message = "ok"
|
|
respondWithJSON(w, http.StatusOK, pageResp)
|
|
}
|
|
|
|
// Fail 响应失败
|
|
func Fail(w http.ResponseWriter, err error) {
|
|
var msg string
|
|
// 默认code 500
|
|
httpStatusCode := http.StatusInternalServerError
|
|
|
|
var validationErrs validator.ValidationErrors
|
|
var appErr *errs.AppError
|
|
if errors.As(err, &validationErrs) {
|
|
httpStatusCode = http.StatusBadRequest
|
|
msgs := validatorI18.Translate(err)
|
|
msg = strings.Join(msgs, "; ")
|
|
} else if errors.As(err, &appErr) {
|
|
httpStatusCode = appErr.HTTPCode
|
|
msg = appErr.Msg
|
|
} else {
|
|
msg = err.Error()
|
|
}
|
|
|
|
resp := common.Response{
|
|
Message: msg,
|
|
}
|
|
|
|
respondWithJSON(w, httpStatusCode, resp)
|
|
}
|