-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
190 lines (161 loc) · 4.88 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
"github.com/spf13/cast"
"io"
"net"
"net/http"
"os"
"time"
)
type Req struct {
FileAddress string `json:"fileAddress"`
Name string `json:"name"`
Tc int `json:"tc"`
}
const (
FontPath = "./font/hanyiyongzidingshenggaojianti.ttf"
TemplatePath = "./img/zht.jpeg"
ExecStart = 0
ExecClean = 1
)
var (
requestsTotal = prometheus.NewCounter(prometheus.CounterOpts{
Name: "qrcode_http_requests_total",
Help: "Total number of HTTP requests",
})
requestsTotalVec = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "qrcode_http_requests_total_vec",
Help: "Total number of HTTP requests",
}, []string{"uri"})
)
var exec int
func init() {
prometheus.MustRegister(requestsTotal)
prometheus.MustRegister(requestsTotalVec)
flag.IntVar(&exec, "exec", 0, "0: start server; 1: clean file")
flag.Parse()
}
func uploadFileHandler(w http.ResponseWriter, r *http.Request) {
successUrl := fmt.Sprintf("%s/success", GetGlobalConfig().Domain)
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusInternalServerError)
return
}
defer func() {
_ = r.Body.Close()
}()
var req Req
if err = json.Unmarshal(body, &req); err != nil {
http.Error(w, "Invalid JSON format", http.StatusBadRequest)
return
}
log.Infof("request body :%+v", req)
qrFileName := fmt.Sprintf("%d", time.Now().UnixMilli())
//生成二维码
options := make([]Option, 0)
options = append(options, WithHalftoneSrcFile(fmt.Sprintf("%s/%s.png", "./static", req.FileAddress)))
options = append(options, WithLogoWidth(BIG))
options = append(options, WithName(qrFileName))
options = append(options, WithPath(GetGlobalConfig().TmpPath))
contentUrl := fmt.Sprintf("%s?name=%s&tc=%d&img=%s",
successUrl, req.Name, req.Tc, fmt.Sprintf("%s.%s", qrFileName, DefaultFileType))
qrCode, err := NewQuCodeGen(contentUrl, options...).GenQrCode()
if err != nil {
log.Errorf("gen qr code err")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Infof("resp qrcode:%s, contentUrl:%s", qrCode, contentUrl)
resp, err := json.Marshal(map[string]interface{}{
"code": 200,
"data": fmt.Sprintf("%s%s/%s", GetGlobalConfig().Domain, GetGlobalConfig().TmpPath, qrCode),
})
if err != nil {
log.Errorf("json marshal err")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, _ = w.Write(resp)
return
}
func success(w http.ResponseWriter, r *http.Request) {
tmpUrl := fmt.Sprintf("%s%s", GetGlobalConfig().Domain, GetGlobalConfig().TmpPath)
// 解析查询参数
query := r.URL.Query()
// 获取其他表单字段
name := query.Get("name")
tc := cast.ToInt32(query.Get("tc")) / 1000
sourceImg := query.Get("img")
log.Printf("upload info name:%s, tc:%v, tmpUrl:%s", name, tc, tmpUrl)
img := NewResImg(TemplatePath, []ResImgOption{
WithFontPath(FontPath),
WithFontSize(30),
WithContentImg(ContentImg{
ImagePath: fmt.Sprintf("%s/%s", tmpUrl, sourceImg),
Width: 280,
Height: 280,
LineWidth: 2,
Padding: 10,
X: 367,
Y: 410,
}),
WithContents(GetSuccessContent(name, tc)),
WithDstPath(fmt.Sprintf(".%s/", GetGlobalConfig().TmpPath)),
})
_, fileName, err := img.Gen()
if err != nil {
log.Errorf("img gen err:%s", err)
return
}
redirectUrl := fmt.Sprintf("%s/%s", tmpUrl, fileName)
log.Infof("gen img fileName:%s , redirectUrl:%s", fileName, redirectUrl)
http.Redirect(w, r, redirectUrl, http.StatusFound)
}
func withMetricsHandler(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
requestsTotal.Inc()
requestsTotalVec.WithLabelValues(r.URL.Path).Inc()
}()
f(w, r)
}
}
func runHttp() {
tmpPath := fmt.Sprintf("%s/", GetGlobalConfig().TmpPath)
listen, err := net.Listen("tcp", fmt.Sprintf(":%d", GetGlobalConfig().Port))
if err != nil {
panic(err)
}
mux := http.NewServeMux()
mux.HandleFunc("/qrcode/gen", withMetricsHandler(uploadFileHandler))
mux.HandleFunc("/success", withMetricsHandler(success))
mux.Handle("/static/", http.StripPrefix("/", http.FileServer(http.Dir("."))))
mux.Handle(tmpPath, http.StripPrefix("/", http.FileServer(http.Dir("."))))
mux.Handle("/metrics", promhttp.Handler())
_ = http.Serve(listen, mux)
}
func main() {
InitConfig()
log.Infof("starting server config:%+v, exec:%v", GetGlobalConfig(), exec)
switch exec {
case ExecStart:
_ = os.Mkdir(fmt.Sprintf(".%s/", GetGlobalConfig().TmpPath), os.ModePerm)
go func() {
CleanTask()
}()
runHttp()
case ExecClean:
if err := CleanTmpFile(GetGlobalConfig().TmpPath); err != nil {
log.Errorf("clean tmp file err:%s", err)
}
default:
fmt.Println("exec err")
}
}