package rest import ( "encoding/json" "log" "net/http" "strconv" "github.com/google/uuid" "uvok.de/go/training_fellow/registration" mylog "uvok.de/go/training_fellow/registration/log" ) type RegistrationHandler struct { Service *registration.RegistrationService } // adapter to have multiple methods without repeating type // (I have to implement ServeHTTP) func HandleRegistration(handler *RegistrationHandler) http.Handler { regHandler := func(w http.ResponseWriter, r *http.Request) { handleRegistration(handler, w, r) } return http.HandlerFunc(regHandler) } func HandleGetRegistrations(handler *RegistrationHandler) http.Handler { getRegs := func(w http.ResponseWriter, r *http.Request) { regs, err := handler.Service.GetUnconfirmedRegistrations() if err != nil { w.WriteHeader(http.StatusInternalServerError) return } content, err := json.Marshal(regs) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } w.Write(content) } return http.HandlerFunc(getRegs) } func handleRegistration(handler *RegistrationHandler, rw http.ResponseWriter, req *http.Request) { //bodyReader := http.MaxBytesReader(rw, req.Body, 10) //defer bodyReader.Close() defer req.Body.Close() if req.Method != http.MethodPost { rw.WriteHeader(http.StatusMethodNotAllowed) return } err := req.ParseForm() if err != nil { rw.WriteHeader(http.StatusNotAcceptable) mylog.LogError.Printf("Form Parse: %v\n", err) return } newRegistration := registration.Registration{} newRegistration.Company = req.Form.Get("company") newRegistration.Date = req.Form.Get("date") newRegistration.Email = req.Form.Get("email") newRegistration.FirstName = req.Form.Get("first_name") newRegistration.LastName = req.Form.Get("last_name") newRegistration.TrainingCode = req.Form.Get("training_code") val, err := strconv.ParseBool(req.Form.Get("privacy_acc")) newRegistration.PrivacyPolicyAccepted = false newRegistration.Confirmed = false newRegistration.RegId = uuid.NewString() if err != nil { mylog.LogWarning.Printf("Form Parse Bool: %v\n", err) } else { newRegistration.PrivacyPolicyAccepted = val } log.Printf("New registration: %v", newRegistration) if handler.Service != nil { err = handler.Service.HandleNewRegistration(&newRegistration) if err != nil { rw.WriteHeader(http.StatusInternalServerError) mylog.LogError.Printf("Error submitting the following registration: %v. Error: %v", newRegistration, err) return } } rw.WriteHeader(http.StatusCreated) }