1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
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) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
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)
}
|