-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpersonHandler.go
70 lines (59 loc) · 1.9 KB
/
personHandler.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
)
// Person is a struct decsribing its properties
type Person struct {
Name string `json:"name"`
Birthday string `json:"birthday"`
Occupation string `json:"occupation"`
}
func getPersonHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve people from postgresql database using our `store` interface variable's
// `func (*dbstore) GetPerson` pointer receiver method defined in `store.go` file
personList, err := store.GetPerson()
// Convert the `personList` variable to JSON
personListBytes, err := json.Marshal(personList)
if err != nil {
fmt.Println(fmt.Errorf("Error: %v", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
// Write JSON list of persons to response
w.Write(personListBytes)
}
func createPersonHandler(w http.ResponseWriter, r *http.Request) {
// Parse the HTML form data received in the request
err := r.ParseForm()
if err != nil {
fmt.Println(fmt.Errorf("Error: %v", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
// Extract the field information about the person from the form info
person := Person{}
person.Name = r.Form.Get("name")
person.Birthday = r.Form.Get("birthday")
person.Occupation = r.Form.Get("occupation")
// Write new person details into postgresql database using our `store` interface variable's
// `func (*dbstore) CreatePerson` pointer receiver method defined in `store.go` file
err = store.CreatePerson(&person)
if err != nil {
fmt.Println(err)
}
//Redirect to the originating HTML page
http.Redirect(w, r, "/", http.StatusFound)
}
func getServerHandler(w http.ResponseWriter, r *http.Request) {
serverHostName, err := os.Hostname()
serverHostNameBytes, err := json.Marshal(serverHostName)
if err != nil {
fmt.Println(fmt.Errorf("Error: %v", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(serverHostNameBytes)
}