testhub/server.go

69 lines
1.6 KiB
Go
Raw Normal View History

2022-05-25 12:04:53 +02:00
package main
import (
2022-05-26 09:53:08 +02:00
"encoding/json"
2022-06-16 17:21:04 +02:00
"io/ioutil"
2022-05-25 12:04:53 +02:00
"net/http"
2022-06-23 11:10:41 +02:00
"git.andreafazzi.eu/andrea/testhub/client"
2022-05-26 12:30:53 +02:00
"git.andreafazzi.eu/andrea/testhub/logger"
2022-06-16 17:21:04 +02:00
"git.andreafazzi.eu/andrea/testhub/models"
2022-05-25 12:21:32 +02:00
"git.andreafazzi.eu/andrea/testhub/store"
)
2022-05-25 12:04:53 +02:00
2022-05-25 18:09:54 +02:00
const jsonContentType = "application/json"
2022-06-17 16:02:58 +02:00
type QuizHubCollectorServer struct {
store store.QuizHubCollectorStore
2022-05-25 18:09:54 +02:00
http.Handler
2022-05-25 12:04:53 +02:00
}
2022-06-17 16:02:58 +02:00
func NewQuizHubCollectorServer(store store.QuizHubCollectorStore) *QuizHubCollectorServer {
ps := new(QuizHubCollectorServer)
2022-05-25 18:09:54 +02:00
ps.store = store
router := http.NewServeMux()
2022-06-23 11:10:41 +02:00
router.Handle("/quizzes", logger.WithLogging(http.HandlerFunc(ps.testHandler)))
2022-05-25 18:09:54 +02:00
ps.Handler = router
return ps
2022-05-25 12:04:53 +02:00
}
2022-06-17 16:02:58 +02:00
func (ps *QuizHubCollectorServer) testHandler(w http.ResponseWriter, r *http.Request) {
2022-05-25 12:04:53 +02:00
switch r.Method {
case http.MethodGet:
2022-05-26 09:53:08 +02:00
w.Header().Set("content-type", jsonContentType)
2022-06-23 11:10:41 +02:00
json.NewEncoder(w).Encode(ps.readAllQuizzes(w, r))
2022-05-26 09:53:08 +02:00
2022-05-25 12:04:53 +02:00
case http.MethodPost:
2022-05-26 09:53:08 +02:00
w.WriteHeader(http.StatusAccepted)
2022-06-17 16:02:58 +02:00
json.NewEncoder(w).Encode(ps.createQuiz(w, r))
}
}
2022-06-23 11:10:41 +02:00
func (ps *QuizHubCollectorServer) readAllQuizzes(w http.ResponseWriter, r *http.Request) *client.Response {
2022-06-17 16:02:58 +02:00
tests, err := ps.store.ReadAllQuizzes()
if err != nil {
2022-06-23 11:10:41 +02:00
return &client.Response{Status: "error", Content: err.Error()}
2022-05-25 12:04:53 +02:00
}
2022-06-23 11:10:41 +02:00
return &client.Response{Status: "success", Content: tests}
2022-05-25 12:04:53 +02:00
}
2022-05-25 18:09:54 +02:00
2022-06-17 16:02:58 +02:00
func (ps *QuizHubCollectorServer) createQuiz(w http.ResponseWriter, r *http.Request) *models.Quiz {
2022-06-16 17:21:04 +02:00
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
2022-06-23 11:10:41 +02:00
createQuizReq := new(client.CreateQuizRequest)
2022-06-17 16:02:58 +02:00
err = json.Unmarshal(body, &createQuizReq)
2022-06-16 17:21:04 +02:00
if err != nil {
panic(err)
}
2022-06-17 16:02:58 +02:00
createdQuiz := ps.store.CreateQuiz(createQuizReq)
2022-06-16 17:21:04 +02:00
2022-06-17 16:02:58 +02:00
return createdQuiz
2022-05-25 18:09:54 +02:00
}