-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (61 loc) · 1.66 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
87
88
89
90
91
92
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
func main() {
quizService.Init()
router := mux.NewRouter()
router.HandleFunc("/questions", getQuestions).Methods("GET")
router.HandleFunc("/answers", insertAnswers).Methods("POST", "OPTIONS")
router.HandleFunc("/users/{id}/results", getQuizResults).Methods("GET")
log.Fatal(http.ListenAndServe(":8000", router))
}
func enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, HEAD, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding")
}
func getQuestions(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
questions, err := quizService.GetQuestions()
if err != nil {
fmt.Fprintln(w, err)
return
}
json.NewEncoder(w).Encode(questions)
}
func insertAnswers(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
if (*r).Method == "OPTIONS" {
return
}
var userAnswerContainer *UserAnswerContainer
_ = json.NewDecoder(r.Body).Decode(&userAnswerContainer)
err := quizService.InsertAnswers(userAnswerContainer)
if err != nil {
fmt.Fprintln(w, err)
return
}
}
func getQuizResults(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
params := mux.Vars(r)
userIDStr := params["id"]
userID, err := strconv.Atoi(userIDStr)
if err != nil {
fmt.Fprintln(w, err)
return
}
userReport, err := quizService.GetUserReport(userID)
if err != nil {
fmt.Fprintln(w, err)
return
}
json.NewEncoder(w).Encode(userReport)
}
var quizService QuizService