This repository has been archived on 2019-07-11. You can view files and clone it, but cannot push or open issues or pull requests.
scoreboard/features/handler.go

70 lines
1.9 KiB
Go
Raw Permalink Normal View History

2019-05-27 21:46:09 +00:00
package features
import (
"net/http"
"git.cliffbreak.de/haveachin/scoreboard/ioutil"
"git.cliffbreak.de/haveachin/scoreboard/request/meta"
"git.cliffbreak.de/haveachin/scoreboard/response"
"git.cliffbreak.de/haveachin/scoreboard/service/filter"
"git.cliffbreak.de/haveachin/scoreboard/service/id"
)
func CreateHandler(v interface{}, s Service) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response.APIHandler(w, response.APIHandlerFunc(func() (int, error) {
if err := ioutil.ExtractAndValidateJSON(r.Body, v); err != nil {
return http.StatusBadRequest, err
}
if err := s.Create(v); err != nil {
return http.StatusNotFound, err
}
return response.New(v, meta.ParseFromRequest(r)).Send(w, http.StatusCreated)
}))
})
}
func UpdateHandler(v interface{}, s Service) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response.APIHandler(w, response.APIHandlerFunc(func() (int, error) {
if err := ioutil.ExtractAndValidateJSON(r.Body, v); err != nil {
return http.StatusBadRequest, err
}
id, err := id.ParseFromRequest(r)
if err != nil {
return http.StatusBadRequest, err
}
filter := &filter.Filter{"_id": *id}
if err := s.Update(v, filter); err != nil {
return http.StatusNotFound, err
}
return response.New(nil, meta.ParseFromRequest(r)).Send(w, http.StatusOK)
}))
})
}
func DeleteHandler(v interface{}, s Service) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response.APIHandler(w, response.APIHandlerFunc(func() (int, error) {
id, err := id.ParseFromRequest(r)
if err != nil {
return http.StatusBadRequest, err
}
filter := &filter.Filter{"_id": *id}
if err := s.Delete(v, filter); err != nil {
return http.StatusNotFound, err
}
return response.New(nil, meta.ParseFromRequest(r)).Send(w, http.StatusNoContent)
}))
})
}