-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
69 lines (58 loc) · 1.71 KB
/
handler.go
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
package qr
import (
"html/template"
"net/http"
"github.com/gorilla/mux"
"golang.org/x/exp/slog"
)
type Response struct {
Text string
Code string
Error string
}
type Handler struct {
http.Handler
logger *slog.Logger
tmpl *template.Template
}
func NewHandler(logger *slog.Logger) *Handler {
tmpl := template.Must(template.New("").ParseFiles("qr.html"))
h := Handler{
logger: logger,
tmpl: tmpl,
}
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", h.showForm(nil)).Methods(http.MethodGet)
router.HandleFunc("/", h.generateCode()).Methods(http.MethodPost)
h.Handler = router
return &h
}
// GET /qr
func (h *Handler) showForm(data any) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := h.tmpl.ExecuteTemplate(w, "qr", data); err != nil {
h.logger.Error("failed to execute template", "error", err, "template", "qr")
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}
// POST /qr
func (h *Handler) generateCode() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
h.logger.Info("failed to parse form", "error", err)
w.WriteHeader(http.StatusInternalServerError)
h.showForm(Response{Error: "Something went wrong"}).ServeHTTP(w, r)
return
}
encodedQR, err := GenerateCode(r.Context(), CodeRequest{Text: r.PostFormValue("text"), DataType: r.PostFormValue("data_type")})
if err != nil {
h.logger.Info("failed to generate QR Code", "error", err)
w.WriteHeader(http.StatusInternalServerError)
h.showForm(Response{Error: "Something went wrong"}).ServeHTTP(w, r)
return
}
h.showForm(Response{Text: r.PostFormValue("text"), Code: encodedQR}).ServeHTTP(w, r)
}
}