/
http.go
55 lines (47 loc) · 1.31 KB
/
http.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
package restaurant
import (
"encoding/json"
"log"
"net/http"
"github.com/software-engineering-components/lab3/server/tools"
)
type ClientOrder struct {
TableNamber int `json:"tableNamber"`
Items []*Item `json:"items"`
}
type HttpHandlerFunc http.HandlerFunc
func HttpHandler(store *Store) HttpHandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
handleListMenu(rw, store)
} else if r.Method == "POST" {
handleCreateOrder(r, rw, store)
} else {
rw.WriteHeader(http.StatusMethodNotAllowed)
}
}
}
func handleListMenu(rw http.ResponseWriter, store *Store) {
res, err := store.ListMenu()
if err != nil {
log.Printf("Error(Database Query): %s", err)
tools.WriteJsonInternalError(rw)
return
}
tools.WriteJsonOk(rw, res)
}
func handleCreateOrder(r *http.Request, rw http.ResponseWriter, store *Store) {
var clientOrder *ClientOrder
if err := json.NewDecoder(r.Body).Decode(&clientOrder); err != nil {
log.Printf("Error json caused an error: %s", err)
tools.WriteJsonBadRequest(rw, "Bad JSON payload")
return
}
resOrder, err := store.CreateOrder(clientOrder.TableNamber, clientOrder.Items)
if err == nil {
tools.WriteJsonOk(rw, resOrder)
} else {
log.Printf("Error making query to the db: %s", err)
tools.WriteJsonInternalError(rw)
}
}