-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
86 lines (72 loc) · 2.08 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
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"log"
"net/http"
"os"
"fmt"
)
type Person struct {
ID string `json:"id,omitempty"`
Firstname string `json:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty"`
Status string `json:"status,omitempty"`
}
var people []Person
// get all people
func GetPeople(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(people)
}
// get a single person
func GetPerson(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for _, item := range people {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Person{})
}
// create a new item
func CreatePerson(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var person Person
_ = json.NewDecoder(r.Body).Decode(&person)
person.ID = params["id"]
people = append(people, person)
json.NewEncoder(w).Encode(people)
}
// Delete an item
func DeletePerson(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for index, item := range people {
if item.ID == params["id"] {
people = append(people[:index], people[index+1:]...)
break
}
json.NewEncoder(w).Encode(people)
}
}
func getEnv(w http.ResponseWriter, r *http.Request) {
env := os.Environ()
json.NewEncoder(w).Encode(env)
}
func initPeople() {
people = append(people, Person{ID: "1", Firstname: "John", Lastname: "Doe", Status: "Present" })
people = append(people, Person{ID: "2", Firstname: "Koko", Lastname: "Doe", Status: "Away"})
people = append(people, Person{ID: "3", Firstname: "Francis", Lastname: "Sunday"})
}
// our main function
func main() {
router := mux.NewRouter()
initPeople()
router.HandleFunc("/admin/env", getEnv).Methods("GET")
router.HandleFunc("/people", GetPeople).Methods("GET")
router.HandleFunc("/people/{id}", GetPerson).Methods("GET")
router.HandleFunc("/people/{id}", CreatePerson).Methods("POST")
router.HandleFunc("/people/{id}", DeletePerson).Methods("DELETE")
fmt.Printf("Serving people on port 8000")
log.Fatal(http.ListenAndServe(":8000", router))
}