package api import ( "encoding/json" "net/http" "github.com/rs/zerolog/log" ) type Body map[string]interface{} func ParseBody(r *http.Request) *Body { var body Body _ = json.NewDecoder(r.Body).Decode(&body) defer r.Body.Close() return &body } func (b *Body) String(name string) string { if res, ok := (*b)[name].(string); ok { return res } return "" } func (b *Body) Int(name string) int { if res, ok := (*b)[name].(int); ok { return res } return 0 } func (b *Body) Bool(name string) bool { if res, ok := (*b)[name].(bool); ok { return res } return false } func JSON(w http.ResponseWriter, data interface{}, statusCode int) { b, err := json.Marshal(data) if err != nil { log.Error().Err(err).Msg("cannot decode data when generating a JSON response") w.WriteHeader(http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(statusCode) _, _ = w.Write(b) }