-
Notifications
You must be signed in to change notification settings - Fork 9
/
qr.go
99 lines (89 loc) · 2.46 KB
/
qr.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
package txtdirect
import (
"encoding/hex"
"fmt"
"image/color"
"net/http"
"strconv"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/skip2/go-qrcode"
)
// Qr contains Qr code generator's configuration
type Qr struct {
Enable bool
Size int
BackgroundColor string
ForegroundColor string
RecoveryLevel qrcode.RecoveryLevel
backgroundColor color.Color
foregroundColor color.Color
}
// Redirect handles the requests for "qr" requests
func (qr *Qr) Redirect(w http.ResponseWriter, r *http.Request) error {
Qr, err := qrcode.New(r.Host+r.URL.String(), qr.RecoveryLevel)
if err != nil {
return fmt.Errorf("Couldn't generate the Qr instance: %s", err.Error())
}
if err = qr.ParseColors(); err != nil {
return fmt.Errorf("Coudln't parse colors: %s", err.Error())
}
Qr.BackgroundColor, Qr.ForegroundColor = qr.backgroundColor, qr.foregroundColor
Qr.Write(qr.Size, w)
return nil
}
// ParseColors parses the hex colors in the QR config to color.Color instances
func (qr *Qr) ParseColors() error {
bg, err := hex.DecodeString(qr.BackgroundColor)
if err != nil {
return err
}
qr.backgroundColor = color.RGBA{bg[0], bg[1], bg[2], bg[3]}
fg, _ := hex.DecodeString(qr.ForegroundColor)
if err != nil {
return err
}
qr.foregroundColor = color.RGBA{fg[0], fg[1], fg[2], fg[3]}
return nil
}
// ParseQr parses the config for QR requests
func (qr *Qr) ParseQr(c *caddyfile.Dispenser) error {
switch c.Val() {
case "size":
value, err := strconv.Atoi(c.RemainingArgs()[0])
if err != nil {
return fmt.Errorf("<QR>: Couldn't parse the size")
}
qr.Size = value
case "background":
qr.BackgroundColor = c.RemainingArgs()[0]
case "foreground":
qr.ForegroundColor = c.RemainingArgs()[0]
case "recovery_level":
value, err := strconv.Atoi(c.RemainingArgs()[0])
if err != nil {
return fmt.Errorf("<QR>: Couldn't parse the recovery_level. It should be from 0 to 3")
}
qr.RecoveryLevel = qrcode.RecoveryLevel(value)
default:
return c.ArgErr() // unhandled option for QR config
}
return nil
}
// SetDefaults sets the default values for QR config
func (qr *Qr) SetDefaults() {
if qr.Size == 0 {
qr.Size = 256
}
if qr.BackgroundColor == "" {
qr.BackgroundColor = "ffffffff"
}
if qr.ForegroundColor == "" {
qr.ForegroundColor = "000000ff"
}
if len(qr.BackgroundColor) == 7 {
qr.BackgroundColor = (qr.BackgroundColor + "ff")[1:]
}
if len(qr.ForegroundColor) == 7 {
qr.ForegroundColor = (qr.ForegroundColor + "ff")[1:]
}
}