-
Notifications
You must be signed in to change notification settings - Fork 28
/
course.go
104 lines (89 loc) · 2.28 KB
/
course.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
package handler
import (
"encoding/json"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
var (
courses []Course
)
func init() {
loadCourses("./data/courses.json")
}
func loadCourses(path string) {
if courses != nil {
return
}
if err := readContent(path, &courses); err != nil {
log.Println("Could not read courses data")
}
}
func GetAllCourses(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
query := r.URL.Query()
topics, ok := query["topic"]
if ok {
res := make([]Course, 0)
for _, course := range courses {
if contains(course.Topics, topics) {
res = append(res, course)
}
}
e := json.NewEncoder(w)
e.Encode(res)
return
}
e := json.NewEncoder(w)
e.Encode(courses)
}
func GetCoursesWithInstructorAndAttendee(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
// we don't have to check for multiple instructor because the way our data is structured
// there is no way multiple instructor can be part of same course
_instructor := r.URL.Query().Get("instructor")
instructorID, _ := strconv.Atoi(_instructor)
// but multiple attendee can be part of the same course
// since we gurrantee only valid integer queries will be sent to this route
// we don't need to check if there is value or not.
attendees := r.URL.Query()["attendee"]
res := make([]Course, 0)
for _, course := range courses {
if course.InstructorID == instructorID && containsInt(course.Attendees, attendees) {
res = append(res, course)
}
}
e := json.NewEncoder(w)
e.Encode(res)
}
func GetCoursesByID(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
// this function takes in the request and parses
// all the pathParams from it
// pathParams is a map[string]string
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 *Course
for _, v := range courses {
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)
}