-
Notifications
You must be signed in to change notification settings - Fork 47
/
http-rest-delete.go
120 lines (104 loc) · 2.53 KB
/
http-rest-delete.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
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
const (
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"getEmployees",
"GET",
"/employees",
getEmployees,
},
Route{
"addEmployee",
"POST",
"/employee/add/",
addEmployee,
},
Route{
"deleteEmployee",
"DELETE",
"/employee/delete",
deleteEmployee,
},
}
type Employee struct {
Id string `json:"id"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}
type Employees []Employee
var employees []Employee
func init() {
employees = Employees{
Employee{Id: "1", FirstName: "Foo", LastName: "Bar"},
Employee{Id: "2", FirstName: "Baz", LastName: "Qux"},
}
}
func getEmployees(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(employees)
}
func deleteEmployee(w http.ResponseWriter, r *http.Request) {
employee := Employee{}
err := json.NewDecoder(r.Body).Decode(&employee)
if err != nil {
log.Print("error occurred while decoding employee data :: ", err)
return
}
log.Printf("deleting employee id :: %s with firstName as :: %s and lastName as :: %s ", employee.Id, employee.FirstName, employee.LastName)
index := GetIndex(employee.Id)
employees = append(employees[:index], employees[index+1:]...)
json.NewEncoder(w).Encode(employees)
}
func GetIndex(id string) int {
for i := 0; i < len(employees); i++ {
if employees[i].Id == id {
return i
}
}
return -1
}
func addEmployee(w http.ResponseWriter, r *http.Request) {
employee := Employee{}
err := json.NewDecoder(r.Body).Decode(&employee)
if err != nil {
log.Print("error occurred while decoding employee data :: ", err)
return
}
log.Printf("adding employee id :: %s with firstName as :: %s and lastName as :: %s ", employee.Id, employee.FirstName, employee.LastName)
employees = append(employees, Employee{Id: employee.Id, FirstName: employee.FirstName, LastName: employee.LastName})
json.NewEncoder(w).Encode(employees)
}
func AddRoutes(router *mux.Router) *mux.Router {
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
return router
}
func main() {
muxRouter := mux.NewRouter().StrictSlash(true)
router := AddRoutes(muxRouter)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
if err != nil {
log.Fatal("error starting http server :: ", err)
return
}
}