Files

54 lines
1.2 KiB
Go
Raw Permalink Normal View History

package responses
import (
"encoding/json"
"net/http"
)
type Response struct {
Success bool `json:"success"`
Data interface{} `json:"data,omitempty"`
Error string `json:"error,omitempty"`
Code int `json:"code,omitempty"`
}
func JSON(w http.ResponseWriter, statusCode int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(data)
}
func Success(w http.ResponseWriter, statusCode int, data interface{}) {
JSON(w, statusCode, Response{
Success: true,
Data: data,
})
}
func Error(w http.ResponseWriter, statusCode int, errMsg string) {
JSON(w, statusCode, Response{
Success: false,
Error: errMsg,
Code: statusCode,
})
}
func BadRequest(w http.ResponseWriter, errMsg string) {
Error(w, http.StatusBadRequest, errMsg)
}
func Unauthorized(w http.ResponseWriter, errMsg string) {
Error(w, http.StatusUnauthorized, errMsg)
}
func Forbidden(w http.ResponseWriter, errMsg string) {
Error(w, http.StatusForbidden, errMsg)
}
func NotFound(w http.ResponseWriter, errMsg string) {
Error(w, http.StatusNotFound, errMsg)
}
func InternalServerError(w http.ResponseWriter, errMsg string) {
Error(w, http.StatusInternalServerError, errMsg)
}