blob: 4839675fe28a1a333321ed15f324aed1b90cd529 [file] [log] [blame]
Philipp Schradercdb5cfc2022-02-20 14:57:07 -08001package requests
2
3import (
4 "fmt"
5 "io"
6 "net/http"
7
8 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/error_response"
9 "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/submit_data_scouting"
10 _ "github.com/frc971/971-Robot-Code/scouting/webserver/requests/messages/submit_data_scouting_response"
11 "github.com/frc971/971-Robot-Code/scouting/webserver/server"
12 flatbuffers "github.com/google/flatbuffers/go"
13)
14
15// Handles unknown requests. Just returns a 404.
16func unknown(w http.ResponseWriter, req *http.Request) {
17 w.WriteHeader(http.StatusNotFound)
18}
19
20func respondWithError(w http.ResponseWriter, statusCode int, errorMessage string) {
21 builder := flatbuffers.NewBuilder(1024)
22 builder.Finish((&error_response.ErrorResponseT{
23 ErrorMessage: errorMessage,
24 }).Pack(builder))
25 w.WriteHeader(statusCode)
26 w.Write(builder.FinishedBytes())
27}
28
29func respondNotImplemented(w http.ResponseWriter) {
30 respondWithError(w, http.StatusNotImplemented, "")
31}
32
33// TODO(phil): Can we turn this into a generic?
34func parseSubmitDataScouting(w http.ResponseWriter, buf []byte) (*submit_data_scouting.SubmitDataScouting, bool) {
35 success := true
36 defer func() {
37 if r := recover(); r != nil {
38 respondWithError(w, http.StatusBadRequest, fmt.Sprintf("Failed to parse SubmitDataScouting: %v", r))
39 success = false
40 }
41 }()
42 result := submit_data_scouting.GetRootAsSubmitDataScouting(buf, 0)
43 return result, success
44}
45
46// Handles a SubmitDataScouting request.
47func submitDataScouting(w http.ResponseWriter, req *http.Request) {
48 requestBytes, err := io.ReadAll(req.Body)
49 if err != nil {
50 respondWithError(w, http.StatusBadRequest, fmt.Sprint("Failed to read request bytes:", err))
51 return
52 }
53
54 _, success := parseSubmitDataScouting(w, requestBytes)
55 if !success {
56 return
57 }
58
59 // TODO(phil): Actually handle the request.
60
61 respondNotImplemented(w)
62}
63
64func HandleRequests(scoutingServer server.ScoutingServer) {
65 scoutingServer.HandleFunc("/requests", unknown)
66 scoutingServer.HandleFunc("/requests/submit/data_scouting", submitDataScouting)
67}