-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
172 lines (135 loc) · 4.15 KB
/
main.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"github.com/pborman/uuid"
"github.com/tomogoma/go-rest-service/model"
"io/ioutil"
"log"
"net/http"
"os"
"sort"
"strconv"
)
var persons = make(map[string]model.Person)
func main() {
r := mux.NewRouter()
r.PathPrefix("/persons/{id}").Methods(http.MethodGet).HandlerFunc(HandleGetPerson)
r.PathPrefix("/persons/{id}").Methods(http.MethodPut).HandlerFunc(HandleUpdatePerson)
r.PathPrefix("/persons").Methods(http.MethodGet).HandlerFunc(HandleGetPersons)
r.PathPrefix("/persons").Methods(http.MethodPost).HandlerFunc(HandleCreatePerson)
port := os.Getenv("PORT")
addr := ":" + port
log.Printf("Server is listening at %s", addr)
err := http.ListenAndServe(addr, r)
log.Printf("Server stopped with error: %v", err)
}
func HandleGetPersons(w http.ResponseWriter, r *http.Request) {
pNmbrStr := r.FormValue("pageNumber")
pSizeStr := r.FormValue("pageSize")
pNmbr, err := strconv.Atoi(pNmbrStr)
if err != nil {
pNmbr = 1
}
pSize, err := strconv.Atoi(pSizeStr)
if err != nil {
pNmbr = 100
}
page := model.Page{Number: pNmbr, Size: pSize}
var personsSlc []model.Person
for _, person := range persons {
personsSlc = append(personsSlc, person)
}
sort.SliceStable(personsSlc, func(i, j int) bool {
return personsSlc[i].Age > personsSlc[j].Age
})
endPosn := len(personsSlc)
if len(personsSlc) > page.EndPosition() {
endPosn = page.EndPosition()
}
startIdx := len(personsSlc)
if len(personsSlc) > page.StartIndex() {
startIdx = page.StartIndex()
}
personsRslt := personsSlc[startIdx:endPosn]
w.WriteHeader(http.StatusOK)
w.Header().Set("content-type", "application/json")
err = json.NewEncoder(w).Encode(personsRslt)
if err != nil {
log.Printf("Error encoding results: %v", err)
}
}
func HandleGetPerson(w http.ResponseWriter, r *http.Request) {
personId := mux.Vars(r)["id"]
person, exist := persons[personId]
if !exist {
log.Printf("Person with id %s does not exist", personId)
http.Error(w, "Person with id %s does not exist", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("content-type", "application/json")
err := json.NewEncoder(w).Encode(person)
if err != nil {
log.Printf("Error encoding results: %v", err)
}
}
func HandleCreatePerson(w http.ResponseWriter, r *http.Request) {
newPa := model.Person{}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Unable to read request: %v", err)
http.Error(w, "Something wicked happened, please try again", http.StatusInternalServerError)
return
}
if err := json.Unmarshal(body, &newPa); err != nil {
log.Printf("Invalid json in request: %v", err)
http.Error(w, "Invalid json in request: %v", http.StatusBadRequest)
return
}
newPa.ID = uuid.New()
if err := newPa.Valid(); err != nil {
log.Print(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
persons[newPa.ID] = newPa
w.WriteHeader(http.StatusCreated)
w.Header().Set("content-type", "application/json")
if err := json.NewEncoder(w).Encode(newPa); err != nil {
log.Printf("Unable to encode response: %v", err)
}
}
func HandleUpdatePerson(w http.ResponseWriter, r *http.Request) {
personId := mux.Vars(r)["id"]
oldPerson, exist := persons[personId]
if !exist {
log.Printf("Person with id %s does not exist", personId)
http.Error(w, "Person with id %s does not exist", http.StatusNotFound)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Unable to read request: %v", err)
http.Error(w, "Something wicked happened, please try again", http.StatusInternalServerError)
return
}
newPa := model.Person{}
if err := json.Unmarshal(body, &newPa); err != nil {
log.Printf("Invalid json in request: %v", err)
http.Error(w, "Invalid json in request: %v", http.StatusBadRequest)
return
}
newPa.ID = oldPerson.ID
if err := newPa.Valid(); err != nil {
log.Print(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
persons[newPa.ID] = newPa
w.WriteHeader(http.StatusCreated)
w.Header().Set("content-type", "application/json")
if err := json.NewEncoder(w).Encode(newPa); err != nil {
log.Printf("Unable to encode response: %v", err)
}
}