server.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "git.andreafazzi.eu/andrea/testhub/client"
  7. "git.andreafazzi.eu/andrea/testhub/logger"
  8. "git.andreafazzi.eu/andrea/testhub/models"
  9. "git.andreafazzi.eu/andrea/testhub/store"
  10. )
  11. const jsonContentType = "application/json"
  12. type QuizHubCollectorServer struct {
  13. store store.QuizHubCollectorStore
  14. http.Handler
  15. }
  16. func NewQuizHubCollectorServer(store store.QuizHubCollectorStore) *QuizHubCollectorServer {
  17. ps := new(QuizHubCollectorServer)
  18. ps.store = store
  19. router := http.NewServeMux()
  20. router.Handle("/quizzes", logger.WithLogging(http.HandlerFunc(ps.testHandler)))
  21. ps.Handler = router
  22. return ps
  23. }
  24. func (ps *QuizHubCollectorServer) testHandler(w http.ResponseWriter, r *http.Request) {
  25. switch r.Method {
  26. case http.MethodGet:
  27. w.Header().Set("content-type", jsonContentType)
  28. json.NewEncoder(w).Encode(ps.readAllQuizzes(w, r))
  29. case http.MethodPost:
  30. w.WriteHeader(http.StatusAccepted)
  31. json.NewEncoder(w).Encode(ps.createQuiz(w, r))
  32. }
  33. }
  34. func (ps *QuizHubCollectorServer) readAllQuizzes(w http.ResponseWriter, r *http.Request) *client.Response {
  35. tests, err := ps.store.ReadAllQuizzes()
  36. if err != nil {
  37. return &client.Response{Status: "error", Content: err.Error()}
  38. }
  39. return &client.Response{Status: "success", Content: tests}
  40. }
  41. func (ps *QuizHubCollectorServer) createQuiz(w http.ResponseWriter, r *http.Request) *models.Quiz {
  42. body, err := ioutil.ReadAll(r.Body)
  43. if err != nil {
  44. panic(err)
  45. }
  46. createQuizReq := new(client.CreateQuizRequest)
  47. err = json.Unmarshal(body, &createQuizReq)
  48. if err != nil {
  49. panic(err)
  50. }
  51. createdQuiz := ps.store.CreateQuiz(createQuizReq)
  52. return createdQuiz
  53. }