-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.update.go
52 lines (38 loc) · 1.01 KB
/
handlers.update.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package server
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/go-chi/chi"
"github.com/gofrs/uuid"
"github.com/sirupsen/logrus"
"go.jlucktay.dev/rest-api/pkg/storage"
)
func (s *Server) updatePaymentByID() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := uuid.FromStringOrNil(chi.URLParam(r, "id"))
if id == uuid.Nil {
http.Error(w, "Invalid ID.", http.StatusNotFound) // 404
return
}
if r.ContentLength == 0 {
http.Error(w, "Empty request body.", http.StatusBadRequest) // 400
return
}
bodyBytes, errRead := ioutil.ReadAll(r.Body)
if errRead != nil {
logrus.Fatal(errRead)
}
defer r.Body.Close()
var payment storage.Payment
errUm := json.Unmarshal(bodyBytes, &payment)
if errUm != nil {
logrus.Fatal(errUm)
}
if errUpdate := s.Storage.Update(id, payment); errUpdate == nil {
w.WriteHeader(http.StatusNoContent) // 204
return
}
http.Error(w, (&storage.NotFoundError{ID: id}).Error(), http.StatusNotFound) // 404
}
}