-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
executable file
·82 lines (65 loc) · 2.1 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
// Code generated by hertz generator.
package main
import (
"bufio"
"bytes"
"context"
"os"
"time"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/middlewares/server/basic_auth"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/bytebufferpool"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/hertz-contrib/logger/accesslog"
"github.com/hertz-contrib/requestid"
"github.com/hertz-contrib/swagger"
swaggerFiles "github.com/swaggo/files"
"github.com/Dup4/domprinter/biz/dal"
_ "github.com/Dup4/domprinter/swagger"
)
// @BasePath /
// @schemes http
func main() {
dal.Init()
h := server.Default()
h.
Use(requestid.New()).
Use(
accesslog.New(
accesslog.WithAccessLogFunc(hlog.CtxInfof),
accesslog.WithTimeFormat(time.RFC3339Nano),
accesslog.WithFormat(getAccessLogFormat()),
),
)
initBasicAuth(h)
register(h)
h.GET("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler))
h.Spin()
}
func initBasicAuth(h *server.Hertz) {
authUsername := os.Getenv("AUTH_USERNAME")
authPassword := os.Getenv("AUTH_PASSWORD")
accesslog.Tags["requestID"] = func(ctx context.Context, c *app.RequestContext, buf *bytebufferpool.ByteBuffer) (int, error) {
return buf.WriteString(requestid.Get(c))
}
if len(authUsername) > 0 && len(authPassword) > 0 {
h.Use(basic_auth.BasicAuth(map[string]string{
authUsername: authPassword,
}))
}
}
func getAccessLogFormat() string {
var buf bytes.Buffer
writer := bufio.NewWriter(&buf)
writer.WriteString("[${time}] [${requestID}] [${status}] [${latency}]")
writer.WriteString(" -")
writer.WriteString(" ${method} ${protocol}://${host}${path}")
writer.WriteString(" [clientIP=${clientIP}] [path=${path}] [route=${route}] [url=${url}]")
writer.WriteString(" [ip=${ip}] [ips=${ips}] [ua=${ua}]")
writer.WriteString(" [bytesSent=${bytesSent}] [bytesReceived=${bytesReceived}]")
writer.WriteString(" [queryParams=${queryParams}] [reqHeaders=${reqHeaders}] [resHeaders=${resHeaders}]")
writer.WriteString(" [reqBody=${body}] [resBody=${resBody}]")
writer.Flush()
return buf.String()
}