t2/routes/capture.go

77 lines
1.7 KiB
Go

package routes
import (
"net/http"
"strconv"
"gitea.henriburau.de/haw-lan/cod4watcher/models"
"gitea.henriburau.de/haw-lan/cod4watcher/views/capture"
"github.com/go-chi/chi"
)
func (s *Server) HandleCapture(w http.ResponseWriter, r *http.Request) error {
captureString := chi.URLParam(r, "captureID")
captureID, err := strconv.Atoi(captureString)
if err != nil {
return err
}
foundCapture, err := s.cs.GetCaptureById(captureID)
if err != nil {
return err
}
return Render(w, r, capture.Capture(foundCapture))
}
func (s *Server) HandleCaptureForm(w http.ResponseWriter, r *http.Request) error {
return Render(w, r, capture.CaptureForm(capture.CaptureFormValues{}, map[string]string{}))
}
func (s *Server) HandleCaptureCreate(w http.ResponseWriter, r *http.Request) error {
formValues, errors := parseCaptureFormAndValidate(r)
if len(errors) > 0 {
return Render(w, r, capture.CaptureForm(formValues, errors))
}
capture := &models.Capture{
Host: formValues.Host,
Port: formValues.Port,
Name: formValues.Name,
Active: true,
}
err := s.cs.CreateCapture(r.Context(), capture)
if err != nil {
return err
}
return hxRedirect(w, r, "/")
}
func parseCaptureFormAndValidate(r *http.Request) (capture.CaptureFormValues, map[string]string) {
r.ParseForm()
formValues := capture.CaptureFormValues{
Host: r.FormValue("host"),
Port: r.FormValue("port"),
Name: r.FormValue("name"),
}
errors := map[string]string{}
if len(formValues.Host) <= 0 {
errors["host"] = "Host needs to be set"
}
if len(formValues.Port) <= 0 {
errors["port"] = "Port needs to be set"
}
if len(formValues.Name) < 5 || len(formValues.Name) > 50 {
errors["name"] = "Name needs to be between 5 and 50 characters long"
}
return formValues, errors
}