59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"net/http"
|
|
|
|
"git.andreafazzi.eu/andrea/testhub/logger"
|
|
"git.andreafazzi.eu/andrea/testhub/models"
|
|
"git.andreafazzi.eu/andrea/testhub/store"
|
|
)
|
|
|
|
const jsonContentType = "application/json"
|
|
|
|
type TestHubCollectorServer struct {
|
|
store store.TestHubCollectorStore
|
|
http.Handler
|
|
}
|
|
|
|
func NewTestHubCollectorServer(store store.TestHubCollectorStore) *TestHubCollectorServer {
|
|
ps := new(TestHubCollectorServer)
|
|
ps.store = store
|
|
|
|
router := http.NewServeMux()
|
|
|
|
router.Handle("/tests", logger.WithLogging(http.HandlerFunc(ps.testHandler)))
|
|
|
|
ps.Handler = router
|
|
|
|
return ps
|
|
}
|
|
|
|
func (ps *TestHubCollectorServer) testHandler(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
w.Header().Set("content-type", jsonContentType)
|
|
json.NewEncoder(w).Encode(ps.store.GetTests())
|
|
|
|
case http.MethodPost:
|
|
w.WriteHeader(http.StatusAccepted)
|
|
json.NewEncoder(w).Encode(ps.createTest(w, r))
|
|
}
|
|
}
|
|
|
|
func (ps *TestHubCollectorServer) createTest(w http.ResponseWriter, r *http.Request) *models.Test {
|
|
body, err := ioutil.ReadAll(r.Body)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
createTestReq := new(store.CreateTestRequest)
|
|
err = json.Unmarshal(body, &createTestReq)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
createdTest := ps.store.CreateTest(createTestReq)
|
|
|
|
return createdTest
|
|
}
|