-
Notifications
You must be signed in to change notification settings - Fork 28
/
instructor.go
78 lines (65 loc) · 1.41 KB
/
instructor.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
package handler
import (
"encoding/json"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
var (
instructors []Instructor
)
func init() {
loadInstructors("./data/instructors.json")
}
func loadInstructors(path string) {
if err := readContent(path, &instructors); err != nil {
log.Println("Could not read instructors data")
}
}
func GetAllInstructors(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
query := r.URL.Query()
expertise, ok := query["expertise"]
// the key was found.
if ok {
res := make([]Instructor, 0)
for _, instructor := range instructors {
if contains(instructor.Expertise, expertise) {
res = append(res, instructor)
}
}
e := json.NewEncoder(w)
e.Encode(res)
return
}
e := json.NewEncoder(w)
e.Encode(instructors)
}
func GetInstructorByID(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
pathParams := mux.Vars(r)
id := -1
var err error
if val, ok := pathParams["id"]; ok {
id, err = strconv.Atoi(val)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error": "need a valid id"}`))
return
}
}
var data *Instructor
for _, v := range instructors {
if v.ID == id {
data = &v
break
}
}
if data == nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(`{"error": "not found"}`))
}
e := json.NewEncoder(w)
e.Encode(data)
}