71a6bc4aa4
- 分类管理:支持分类的增删改查 - 单词管理:支持单词的增删改查,包含音标、释义、例句等字段 - 更新 README 项目说明 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
41 lines
1.2 KiB
Go
41 lines
1.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
// RespondJSON writes a JSON response with the given status code.
|
|
func RespondJSON(w http.ResponseWriter, status int, data any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(data)
|
|
}
|
|
|
|
// RespondSuccess returns the common success envelope.
|
|
func RespondSuccess(w http.ResponseWriter, data any) {
|
|
RespondJSON(w, http.StatusOK, modelsAPIResponse{Code: 0, Message: "ok", Data: data})
|
|
}
|
|
|
|
// RespondError returns the common error envelope.
|
|
func RespondError(w http.ResponseWriter, status int, code int, message string) {
|
|
RespondJSON(w, status, modelsAPIResponse{Code: code, Message: message, Data: nil})
|
|
}
|
|
|
|
// MapError maps repository/ service errors to HTTP status and code.
|
|
func MapError(err error) (status int, code int, message string) {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return http.StatusNotFound, 10001, "resource not found"
|
|
}
|
|
return http.StatusInternalServerError, 10000, "internal server error"
|
|
}
|
|
|
|
type modelsAPIResponse struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Data any `json:"data"`
|
|
}
|