68 lines
1.6 KiB
Go
68 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"net/http"
|
|
|
|
"git.andreafazzi.eu/andrea/testhub/client"
|
|
"git.andreafazzi.eu/andrea/testhub/logger"
|
|
"git.andreafazzi.eu/andrea/testhub/models"
|
|
"git.andreafazzi.eu/andrea/testhub/store"
|
|
)
|
|
|
|
const jsonContentType = "application/json"
|
|
|
|
type QuizHubCollectorServer struct {
|
|
store store.QuizHubCollectorStore
|
|
http.Handler
|
|
}
|
|
|
|
func NewQuizHubCollectorServer(store store.QuizHubCollectorStore) *QuizHubCollectorServer {
|
|
ps := new(QuizHubCollectorServer)
|
|
ps.store = store
|
|
|
|
router := http.NewServeMux()
|
|
|
|
router.Handle("/quizzes", logger.WithLogging(http.HandlerFunc(ps.testHandler)))
|
|
|
|
ps.Handler = router
|
|
|
|
return ps
|
|
}
|
|
|
|
func (ps *QuizHubCollectorServer) testHandler(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
w.Header().Set("content-type", jsonContentType)
|
|
json.NewEncoder(w).Encode(ps.readAllQuizzes(w, r))
|
|
|
|
case http.MethodPost:
|
|
w.WriteHeader(http.StatusAccepted)
|
|
json.NewEncoder(w).Encode(ps.createQuiz(w, r))
|
|
}
|
|
}
|
|
|
|
func (ps *QuizHubCollectorServer) readAllQuizzes(w http.ResponseWriter, r *http.Request) *client.Response {
|
|
tests, err := ps.store.ReadAllQuizzes()
|
|
if err != nil {
|
|
return &client.Response{Status: "error", Content: err.Error()}
|
|
}
|
|
return &client.Response{Status: "success", Content: tests}
|
|
}
|
|
|
|
func (ps *QuizHubCollectorServer) createQuiz(w http.ResponseWriter, r *http.Request) *models.Quiz {
|
|
body, err := ioutil.ReadAll(r.Body)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
createQuizReq := new(client.CreateQuizRequest)
|
|
err = json.Unmarshal(body, &createQuizReq)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
createdQuiz := ps.store.CreateQuiz(createQuizReq)
|
|
|
|
return createdQuiz
|
|
}
|