-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.go
70 lines (60 loc) · 1.37 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
package main
import (
"bytes"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/qr"
"image/png"
"log"
"net/http"
"net/url"
"strconv"
)
func main() {
http.HandleFunc("/", QrGenerator)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func QrGenerator(w http.ResponseWriter, r *http.Request) {
data := r.URL.Query().Get("data")
if data == "" {
http.Error(w, "", http.StatusBadRequest)
return
}
s, err := url.QueryUnescape(data)
if err != nil {
http.Error(w, "", http.StatusBadRequest)
return
}
code, err := qr.Encode(s, qr.L, qr.Auto)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
size := r.URL.Query().Get("size")
if size == "" {
size = "250"
}
intsize, err := strconv.Atoi(size)
if err != nil {
intsize = 250
}
// Scale the barcode to the appropriate size
code, err = barcode.Scale(code, intsize, intsize)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
buffer := new(bytes.Buffer)
if err := png.Encode(buffer, code); err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
if _, err := w.Write(buffer.Bytes()); err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
}