craban/server/api/utils.go

43 lines
825 B
Go

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 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)
}