44 lines
1.5 KiB
Go
44 lines
1.5 KiB
Go
package httpx
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"common/types"
|
|
"common/codes"
|
|
)
|
|
|
|
func WriteJSON(w http.ResponseWriter, r *http.Request, status int, ok bool, code int, msg string, data interface{}) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
json.NewEncoder(w).Encode(types.Response{Status: ok, Message: msg, Code: code, RequestID: RequestIDFromContext(r), Data: data})
|
|
}
|
|
|
|
func OK(w http.ResponseWriter, r *http.Request, data interface{}) {
|
|
WriteJSON(w, r, http.StatusOK, true, codes.ValueOK, string(codes.OK), data)
|
|
}
|
|
|
|
func Created(w http.ResponseWriter, r *http.Request, data interface{}) {
|
|
WriteJSON(w, r, http.StatusCreated, true, codes.ValueOK, string(codes.OK), data)
|
|
}
|
|
|
|
func BadRequest(w http.ResponseWriter, r *http.Request, msg string) {
|
|
WriteJSON(w, r, http.StatusBadRequest, false, codes.ValueInvalidInput, msg, nil)
|
|
}
|
|
|
|
func Unauthorized(w http.ResponseWriter, r *http.Request, msg string) {
|
|
WriteJSON(w, r, http.StatusUnauthorized, false, codes.ValueUnauthorized, msg, nil)
|
|
}
|
|
|
|
func Conflict(w http.ResponseWriter, r *http.Request, msg string) {
|
|
WriteJSON(w, r, http.StatusConflict, false, codes.ValueConflict, msg, nil)
|
|
}
|
|
|
|
func MethodNotAllowed(w http.ResponseWriter, r *http.Request, msg string) {
|
|
WriteJSON(w, r, http.StatusMethodNotAllowed, false, codes.ValueMethodNotAllowed, msg, nil)
|
|
}
|
|
|
|
func InternalError(w http.ResponseWriter, r *http.Request) {
|
|
WriteJSON(w, r, http.StatusInternalServerError, false, codes.ValueInternalError, string(codes.InternalError), nil)
|
|
}
|