this repo has no description
1package src
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "strconv"
9)
10
11var jsonContentType = "application/json"
12
13// ERRORS
14var ErrIDNotFound = fmt.Errorf("ID not found")
15var ErrInsertPerson = fmt.Errorf("Error inserting person")
16var ErrQueryParamObrigatory = fmt.Errorf("Missing query param 't' in request")
17var ErrSearchPeople = fmt.Errorf("Failed to search for people")
18
19type httpServer struct {
20 People *People
21 db *DB
22}
23
24func NewHTTPServer(addr string, db *DB) *http.Server {
25 server := &httpServer{
26 People: &People{},
27 db: db,
28 }
29
30 r := &http.ServeMux{}
31 r.HandleFunc("GET /pessoas/{id}", server.handleGet)
32 r.HandleFunc("POST /pessoas", server.handlePost)
33 r.HandleFunc("GET /pessoas", server.handleSearch)
34 r.HandleFunc("GET /contagem-pessoas", server.handleCount)
35
36 return &http.Server{
37 Addr: addr,
38 Handler: r,
39 }
40}
41
42type IDDocument struct {
43 Id string `json:"id"`
44}
45
46func (h *httpServer) handleGet(w http.ResponseWriter, req *http.Request) {
47 id := req.PathValue("id")
48
49 person, err := h.People.Get(h.db, id)
50 if err != nil {
51 fmt.Printf("Error getting person %s\n", err)
52 http.Error(w, ErrIDNotFound.Error(), http.StatusBadRequest)
53 return
54 }
55
56 w.Header().Set("Content-Type", jsonContentType)
57 json.NewEncoder(w).Encode(person)
58}
59
60func (h *httpServer) handlePost(w http.ResponseWriter, req *http.Request) {
61 var newPerson InsertPerson
62 err := json.NewDecoder(req.Body).Decode(&newPerson)
63 if err != nil {
64 http.Error(w, err.Error(), http.StatusBadRequest)
65 return
66 }
67
68 id, err := h.People.Insert(h.db, newPerson)
69 if err != nil {
70 fmt.Printf("Error insert person %s\n", err)
71 http.Error(w, ErrInsertPerson.Error(), http.StatusBadRequest)
72 return
73 }
74
75 res := IDDocument{Id: id}
76 w.Header().Set("Content-Type", jsonContentType)
77 json.NewEncoder(w).Encode(res)
78}
79
80func (h *httpServer) handleCount(w http.ResponseWriter, req *http.Request) {
81 val, _ := h.db.CountAllPeople()
82 io.WriteString(w, strconv.Itoa(val))
83}
84
85func (h *httpServer) handleSearch(w http.ResponseWriter, req *http.Request) {
86 searchParam := req.URL.Query().Get("t")
87
88 if searchParam == "" {
89 http.Error(w, ErrQueryParamObrigatory.Error(), http.StatusBadRequest)
90 return
91 }
92
93 people, err := h.People.Search(h.db, searchParam)
94 if err != nil {
95 fmt.Printf("Error searching for people %s\n", err)
96 http.Error(w, ErrSearchPeople.Error(), http.StatusBadRequest)
97 return
98 }
99
100 w.Header().Set("Content-Type", jsonContentType)
101 json.NewEncoder(w).Encode(people)
102}