-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
108 lines (90 loc) · 2.48 KB
/
main.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"embed"
"html/template"
"log"
"net/http"
"strings"
"github.com/emersion/go-vcard"
"github.com/skip2/go-qrcode"
)
var version = "dev"
//go:embed templates/*
var content embed.FS
type Page struct {
Title string
Version string
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", homeHandler)
mux.HandleFunc("/contactCardGeneratorHandler/", contactCardGeneratorHandler)
mux.HandleFunc("/urlGeneratorHandler/", urlGeneratorHandler)
mux.HandleFunc("/health/live", healthHandler)
mux.HandleFunc("/health/ready", healthHandler)
log.Printf("Server (version: %v) started, listening on :8080", version)
http.ListenAndServe(":8080", mux)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request")
p := Page{Title: "QR Code Generator", Version: version}
t, _ := template.ParseFS(content, "templates/generator.html")
t.Execute(w, p)
}
func contactCardGeneratorHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Fatalln(err)
}
vc := vcard.Card{}
vc.AddValue(vcard.FieldVersion, "3.0")
vc.AddName(&vcard.Name{
FamilyName: r.FormValue("lastname"),
GivenName: r.FormValue("firstname"),
})
vc.AddAddress(&vcard.Address{
Locality: r.FormValue("locality"),
StreetAddress: r.FormValue("street"),
PostalCode: r.FormValue("postcode"),
})
vc.AddValue(vcard.FieldOrganization, r.FormValue("organization"))
vc.AddValue(vcard.FieldTitle, r.FormValue("title"))
vc.AddValue(vcard.FieldEmail, r.FormValue("email"))
vc.AddValue(vcard.FieldTelephone, r.FormValue("phone"))
encodedVCard := new(strings.Builder)
enc := vcard.NewEncoder(encodedVCard)
err = enc.Encode(vc)
if err != nil {
log.Fatalln(err)
}
log.Println("Generating QR-Code for:", encodedVCard.String())
qr, err := qrcode.Encode(encodedVCard.String(), qrcode.Medium, 256)
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "image/png")
_, err = w.Write(qr)
if err != nil {
log.Fatal(err)
}
}
func urlGeneratorHandler(w http.ResponseWriter, r *http.Request) {
url := r.FormValue("url")
log.Println("Generating QR-Code for:", url)
err := r.ParseForm()
if err != nil {
log.Fatalln(err)
}
qr, err := qrcode.Encode(r.FormValue("url"), qrcode.Medium, 256)
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "image/png")
_, err = w.Write(qr)
if err != nil {
log.Fatal(err)
}
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}