-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
134 lines (108 loc) · 2.38 KB
/
handler.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
package file
import (
"context"
"net"
"net/http"
"sync"
"time"
"github.com/dolfly/core/handler"
md "github.com/dolfly/core/metadata"
xmetrics "github.com/dolfly/x/metrics"
"github.com/dolfly/x/registry"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func init() {
registry.HandlerRegistry().Register("metrics", NewHandler)
}
type metricsHandler struct {
handler http.Handler
server *http.Server
ln *singleConnListener
md metadata
options handler.Options
}
func NewHandler(opts ...handler.Option) handler.Handler {
options := handler.Options{}
for _, opt := range opts {
opt(&options)
}
return &metricsHandler{
options: options,
}
}
func (h *metricsHandler) Init(md md.Metadata) (err error) {
if err = h.parseMetadata(md); err != nil {
return
}
xmetrics.Init(xmetrics.NewMetrics())
h.handler = promhttp.Handler()
mux := http.NewServeMux()
mux.Handle(h.md.path, http.HandlerFunc(h.handleFunc))
h.server = &http.Server{
Handler: mux,
}
h.ln = &singleConnListener{
conn: make(chan net.Conn),
done: make(chan struct{}),
}
go h.server.Serve(h.ln)
return
}
func (h *metricsHandler) Handle(ctx context.Context, conn net.Conn, opts ...handler.HandleOption) error {
h.ln.send(conn)
return nil
}
func (h *metricsHandler) Close() error {
return h.server.Close()
}
func (h *metricsHandler) handleFunc(w http.ResponseWriter, r *http.Request) {
if auther := h.options.Auther; auther != nil {
u, p, _ := r.BasicAuth()
if _, ok := auther.Authenticate(r.Context(), u, p); !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
log := h.options.Logger
start := time.Now()
h.handler.ServeHTTP(w, r)
log = log.WithFields(map[string]any{
"remote": r.RemoteAddr,
"duration": time.Since(start),
})
log.Debugf("%s %s", r.Method, r.RequestURI)
}
type singleConnListener struct {
conn chan net.Conn
addr net.Addr
done chan struct{}
mu sync.Mutex
}
func (l *singleConnListener) Accept() (net.Conn, error) {
select {
case conn := <-l.conn:
return conn, nil
case <-l.done:
return nil, net.ErrClosed
}
}
func (l *singleConnListener) Close() error {
l.mu.Lock()
defer l.mu.Unlock()
select {
case <-l.done:
default:
close(l.done)
}
return nil
}
func (l *singleConnListener) Addr() net.Addr {
return l.addr
}
func (l *singleConnListener) send(conn net.Conn) {
select {
case l.conn <- conn:
case <-l.done:
return
}
}