-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.go
94 lines (75 loc) · 2.42 KB
/
api.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"google.golang.org/appengine"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
// User struct will be used for the json params.
type User struct {
ID string `json:"id,omitempty"`
Firstname string `json:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty"`
Age int `json:"age,omitempty"`
}
var users []User
func main() {
//Local array to have something to test.
users = append(users, User{ID: "1", Firstname: "James", Lastname: "Hetfield", Age: 56})
users = append(users, User{ID: "2", Firstname: "Lars", Lastname: "Ulrich", Age: 55})
users = append(users, User{ID: "3", Firstname: "Kirk", Lastname: "Hammett", Age: 56})
users = append(users, User{ID: "4", Firstname: "Robert", Lastname: "Trujillo", Age: 55})
var apirouter = mux.NewRouter()
apirouter.HandleFunc("/", health).Methods("GET")
apirouter.HandleFunc("/users", GetUsers).Methods("GET")
apirouter.HandleFunc("/users/{id}", GetUserID).Methods("GET")
apirouter.HandleFunc("/users/{id}", DelUser).Methods("DELETE")
apirouter.HandleFunc("/users/{id}", CreateUser).Methods("POST")
fmt.Println("API up on port 8080")
//Allowing all CORS calls currently.
log.Fatal(http.ListenAndServe(":8080", handlers.CORS()(apirouter)))
appengine.Main()
}
// Health check. Polling / outputs "ok"
func health(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode("ok")
}
// GetUsers will get all the users from the array.
func GetUsers(w http.ResponseWriter, req *http.Request) {
json.NewEncoder(w).Encode(users)
}
// GetUserID will get users by ID.
func GetUserID(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
for _, item := range users {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
// if the id is not found, still empty object
json.NewEncoder(w).Encode(&User{})
}
// CreateUser will create a user.
func CreateUser(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
var user User
_ = json.NewDecoder(req.Body).Decode(&user)
user.ID = params["id"]
users = append(users, user)
json.NewEncoder(w).Encode(users)
}
// DelUser will remove a user.
func DelUser(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
for index, item := range users {
if item.ID == params["id"] {
users = append(users[:index], users[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(users)
}