Repository navigation
Expand file tree
/
Copy pathmiddleware.go
More file actions
79 lines (70 loc) 路 1.94 KB
/
Copy pathmiddleware.go
File metadata and controls
79 lines (70 loc) 路 1.94 KB
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
package main
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"time"
)
// statusWriter wraps ResponseWriter to capture the status code.
type statusWriter struct {
http.ResponseWriter
code int
}
func (w *statusWriter) WriteHeader(code int) {
w.code = code
w.ResponseWriter.WriteHeader(code)
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, code: 200}
next.ServeHTTP(sw, r)
slog.Info("request",
"method", r.Method,
"path", r.URL.Path,
"status", sw.code,
"ms", time.Since(start).Milliseconds(),
)
})
}
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if token != "" {
auth := r.Header.Get("Authorization")
if auth != "Bearer "+token {
jsonErr(w, 401, fmt.Errorf("unauthorized"))
return
}
}
next.ServeHTTP(w, r)
})
}
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
if r.Method == "OPTIONS" {
w.WriteHeader(204)
return
}
next.ServeHTTP(w, r)
})
}
// cancelOnClientDone cancels the given cancel func when the HTTP client disconnects.
func cancelOnClientDone(reqCtx context.Context, cancel context.CancelFunc) {
<-reqCtx.Done()
cancel()
}
func jsonResp(w http.ResponseWriter, code int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(data); err != nil {
slog.Error("json encode", "err", err)
}
}
func jsonErr(w http.ResponseWriter, code int, err error) {
jsonResp(w, code, map[string]string{"error": err.Error()})
}