Initial project snapshot
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func WriteJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
|
||||
func WriteError(w http.ResponseWriter, status int, message string) {
|
||||
traceID := ensureTraceID(w)
|
||||
WriteJSON(w, status, ErrorResponse{
|
||||
Error: NewErrorMessage(status, message, nil, traceID),
|
||||
})
|
||||
}
|
||||
|
||||
func WriteErrorMessage(w http.ResponseWriter, status int, message any) {
|
||||
traceID := ensureTraceID(w)
|
||||
switch payload := message.(type) {
|
||||
case string:
|
||||
WriteJSON(w, status, ErrorResponse{
|
||||
Error: NewErrorMessage(status, payload, nil, traceID),
|
||||
})
|
||||
case ErrorResponse:
|
||||
payload.Error.TraceID = traceID
|
||||
WriteJSON(w, status, payload)
|
||||
case *ErrorResponse:
|
||||
if payload == nil {
|
||||
WriteJSON(w, status, ErrorResponse{
|
||||
Error: NewErrorMessage(status, "", nil, traceID),
|
||||
})
|
||||
return
|
||||
}
|
||||
payload.Error.TraceID = traceID
|
||||
WriteJSON(w, status, payload)
|
||||
default:
|
||||
WriteJSON(w, status, ErrorResponse{
|
||||
Error: NewErrorMessage(status, "Request failed.", nil, traceID),
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user