pokedex-go/rest/restutils.go

43 lines
1.0 KiB
Go

package rest
import (
"encoding/json"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"net/http"
)
func Json(w http.ResponseWriter, data any) {
bytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
http.Error(w, "Oops, something went wrong", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(bytes)
}
func ProtoJson(w http.ResponseWriter, msg proto.Message) {
bytes, err := protojson.Marshal(msg)
if err != nil {
http.Error(w, "Oops, something went wrong", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(bytes)
}
func BadRequest(w http.ResponseWriter) {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
}
func TooManyRequests(w http.ResponseWriter) {
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
}
func Unauthorized(w http.ResponseWriter) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
}