-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathroutes.go
85 lines (79 loc) · 2.5 KB
/
routes.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"io"
"net/http"
"strconv"
)
func (server *server) routes() {
server.router.HandleFunc("/author/{id:[0-9]+}", otelhttp.NewHandler(server.handleAuthorGet(), "AuthorGet").ServeHTTP).Methods(http.MethodGet)
server.router.HandleFunc("/author/{id:[0-9]+}", otelhttp.NewHandler(server.handleAuthorPostOrPut(), "AuthorPost").ServeHTTP).Methods(http.MethodPost)
server.router.HandleFunc("/author/{id:[0-9]+}", otelhttp.NewHandler(server.handleAuthorPostOrPut(), "AuthorPut").ServeHTTP).Methods(http.MethodPut)
}
func getIdFromRequest(req *http.Request) (id int, err error) {
vars := mux.Vars(req)
if vars["id"] != "" {
id, _ = strconv.Atoi(vars["id"])
} else {
err = fmt.Errorf("id property not present in request")
}
return
}
func (server *server) handleAuthorPostOrPut() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
authorId, err := getIdFromRequest(req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
decoder := json.NewDecoder(req.Body)
decoder.DisallowUnknownFields() // catch unwanted fields
var author Author
err = decoder.Decode(&author)
if err != nil {
// bad JSON or unrecognized json field
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ctx := req.Context()
err, replyAuthor, done := server.persistToStorageLayer(w, author, err, ctx, authorId)
if done {
return
}
encodedAuthor, err := json.Marshal(replyAuthor)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, _ = io.WriteString(w, string(encodedAuthor))
}
}
func (server *server) handleAuthorGet() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
authorId, err := getIdFromRequest(req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ctx := req.Context()
found, storageReplyMap := server.retrieveFromStorageLayer(err, ctx, authorId)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !found {
http.Error(w, fmt.Sprintf("The resource Author with id %d does not exist", authorId), http.StatusNotFound)
return
}
replyAuthor, _ := UpdateAuthorFromMapState(Author{}, storageReplyMap)
encodedAuthor, err := json.Marshal(replyAuthor)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, _ = io.WriteString(w, string(encodedAuthor))
}
}