testhub/server.go

73 lines
1.6 KiB
Go
Raw Permalink 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-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
type Response struct {
Status string `json:"success"`
Content interface{} `json:"content"`
}
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-16 17:21:04 +02:00
router.Handle("/tests", 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-17 16:02:58 +02:00
json.NewEncoder(w).Encode(ps.readAllQuizs(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))
}
}
func (ps *QuizHubCollectorServer) readAllQuizs(w http.ResponseWriter, r *http.Request) *Response {
tests, err := ps.store.ReadAllQuizzes()
if err != nil {
return &Response{"error", err.Error()}
2022-05-25 12:04:53 +02:00
}
2022-06-17 16:02:58 +02:00
return &Response{"success", 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-17 16:02:58 +02:00
createQuizReq := new(store.CreateQuizRequest)
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
}