diff --git a/pkg/gordio/server/calls.go b/pkg/gordio/server/calls.go index 51fe9fc..62bf01c 100644 --- a/pkg/gordio/server/calls.go +++ b/pkg/gordio/server/calls.go @@ -2,17 +2,19 @@ package server import ( "fmt" + "io" "net/http" + "reflect" "time" - - "github.com/go-chi/render" ) +//const timeFormat = "2006-01-02T15:04:05.999Z07:00" + type callUploadRequest struct { Audio []byte `form:"audio"` AudioName string `form:"audioName"` - AudioType time.Time `form:"audioType"` - DateTime string `form:"dateTime"` + AudioType string `form:"audioType"` + DateTime time.Time `form:"dateTime"` Frequencies []int `form:"frequencies"` Frequency int `form:"frequency"` Key string `form:"key"` @@ -32,13 +34,50 @@ func (car *callUploadRequest) Bind(r *http.Request) error { } func (s *Server) routeCallUpload(w http.ResponseWriter, r *http.Request) { - callUpload := new(callUploadRequest) - err := render.Bind(r, callUpload) + call := new(callUploadRequest) + err := fillFields(r, call) if err != nil { - http.Error(w, "cannot bind upload", 500) + http.Error(w, "cannot bind upload "+r.Header.Get("Content-Type")+err.Error(), 500) return } - fmt.Printf("%#v\n", callUpload) + fmt.Printf("%#v\n", call) w.Write([]byte("yay")) } + +func fillFields(r *http.Request, v *callUploadRequest) error { + rv := reflect.ValueOf(v).Elem() + rt := rv.Type() + + for i := 0; i < rv.NumField(); i++ { + f := rv.Field(i) + ff := rt.Field(i).Tag.Get("form") + switch ff { + case "audio": + file, _, err := r.FormFile(ff) + if err != nil { + return err + } + + audioBytes, err := io.ReadAll(file) + if err != nil { + return err + } + + f.SetBytes(audioBytes) + case "dateTime": + t, err := time.Parse(time.RFC3339, r.Form.Get(ff)) + if err != nil { + return err + } + f.Set(reflect.ValueOf(t)) + case "frequencies": + case "frequency", "talkgroup": + case "patches", "sources": + default: + f.SetString(r.Form.Get(ff)) + } + } + + return nil +} diff --git a/pkg/gordio/server/routes.go b/pkg/gordio/server/routes.go index 1148652..17fc847 100644 --- a/pkg/gordio/server/routes.go +++ b/pkg/gordio/server/routes.go @@ -1,6 +1,8 @@ package server import ( + "fmt" + "io" "net/http" "time" @@ -14,6 +16,7 @@ import ( func (s *Server) setupRoutes() { r := s.r + r.Use(middleware.Recoverer) r.Use(middleware.WithValue(database.DBCTXKeyValue, s.db)) r.Group(func(r chi.Router) { @@ -25,6 +28,7 @@ func (s *Server) setupRoutes() { r.Group(func(r chi.Router) { r.Use(rateLimiter()) r.Use(render.SetContentType(render.ContentTypeJSON)) + // r.Use(teeRequest()) // public routes r.Post("/auth", s.routeAuth) r.Post("/api/call-upload", s.routeCallUpload) @@ -40,6 +44,13 @@ func (s *Server) setupRoutes() { }) } +func teeRequest() func(http.Handler) http.Handler { + return middleware.New(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + by, err := io.ReadAll(r.Body) + fmt.Println(string(by), err) + })) +} + func rateLimiter() func(http.Handler) http.Handler { return httprate.LimitByRealIP(100, 1*time.Minute) }