Add backend foundation and config-driven workbench
This commit is contained in:
39
backend/internal/httpx/httpx.go
Normal file
39
backend/internal/httpx/httpx.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"cmr-backend/internal/apperr"
|
||||
)
|
||||
|
||||
func WriteJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
|
||||
func WriteError(w http.ResponseWriter, err error) {
|
||||
if appErr := apperr.From(err); appErr != nil {
|
||||
WriteJSON(w, appErr.Status, map[string]any{
|
||||
"error": map[string]any{
|
||||
"code": appErr.Code,
|
||||
"message": appErr.Message,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusInternalServerError, map[string]any{
|
||||
"error": map[string]any{
|
||||
"code": "internal_error",
|
||||
"message": "internal server error",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func DecodeJSON(r *http.Request, dst any) error {
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
return decoder.Decode(dst)
|
||||
}
|
||||
Reference in New Issue
Block a user