-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
57 lines (46 loc) · 1.39 KB
/
handlers.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
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
func getAllHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Gathering data")
persons, _ := getAll()
json.NewEncoder(w).Encode(persons)
}
func createNewPersonHandler(w http.ResponseWriter, r *http.Request) {
var people People
err := json.NewDecoder(r.Body).Decode(&people)
if err != nil {
log.Println("Can not save new person. Caused by: ", err)
} else {
log.Println("Creating new person")
id := createNewPerson(people.Name, people.Surname, people.Age, people.Hobby, people.Active)
log.Println("Created new person with ID: ", id)
}
}
func getPersonByIDHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id, _ := strconv.Atoi(params["id"])
person, _ := getPersonByID(id)
json.NewEncoder(w).Encode(person)
}
func deletePersonByIDHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id, _ := strconv.Atoi(params["id"])
deletePersonByID(id)
log.Println("Deleted person with ID: ", id)
}
func updatePersonByIDHandler(w http.ResponseWriter, r *http.Request) {
var person People
params := mux.Vars(r)
err := json.NewDecoder(r.Body).Decode(&person)
if err != nil {
log.Println("Error. Caused by: ", err)
}
id, _ := strconv.Atoi(params["id"])
updatePersonByID(id, person.Name, person.Surname, person.Age, person.Hobby, person.Active)
}