37 lines
917 B
Go
37 lines
917 B
Go
package response
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
const (
|
|
CodeOK = 0
|
|
CodeBadRequest = 40000
|
|
CodeUnauthorized = 40100
|
|
CodeForbidden = 40300
|
|
CodeConflict = 40900
|
|
CodeServerError = 50000
|
|
)
|
|
|
|
type Body struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
RequestID string `json:"request_id,omitempty"`
|
|
Data any `json:"data,omitempty"`
|
|
}
|
|
|
|
func OK(w http.ResponseWriter, requestID string, data any) {
|
|
write(w, http.StatusOK, Body{Code: CodeOK, Message: "ok", RequestID: requestID, Data: data})
|
|
}
|
|
|
|
func Fail(w http.ResponseWriter, status int, code int, requestID string, message string) {
|
|
write(w, status, Body{Code: code, Message: message, RequestID: requestID})
|
|
}
|
|
|
|
func write(w http.ResponseWriter, status int, body Body) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(body)
|
|
}
|