47 lines
1.0 KiB
Go
47 lines
1.0 KiB
Go
package httpx
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type Envelope struct {
|
|
Data any `json:"data,omitempty"`
|
|
Error *Error `json:"error,omitempty"`
|
|
TraceID string `json:"traceId"`
|
|
Timestamp int64 `json:"timestamp"`
|
|
}
|
|
|
|
type Error struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
Detail string `json:"detail,omitempty"`
|
|
}
|
|
|
|
func WriteOK(w http.ResponseWriter, traceID string, data any) {
|
|
writeJSON(w, http.StatusOK, Envelope{
|
|
Data: data,
|
|
TraceID: traceID,
|
|
Timestamp: time.Now().UnixMilli(),
|
|
})
|
|
}
|
|
|
|
func WriteError(w http.ResponseWriter, status int, code, message, detail, traceID string) {
|
|
writeJSON(w, status, Envelope{
|
|
Error: &Error{
|
|
Code: code,
|
|
Message: message,
|
|
Detail: detail,
|
|
},
|
|
TraceID: traceID,
|
|
Timestamp: time.Now().UnixMilli(),
|
|
})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, body Envelope) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(body)
|
|
}
|