-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
96 lines (81 loc) · 1.85 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
package httpdump
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/fatih/color"
)
type Handler struct {
format string
}
func NewHandler(format string) *Handler {
return &Handler{format: format}
}
type RequestSummary struct {
Time time.Time `json:"time"`
Method string `json:"method"`
Path string `json:"path"`
IsTLS bool `json:"is_tls"`
Body string `json:"body"`
Header http.Header `json:"header"`
Protocol string `json:"protocol"`
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := h.handle(w, r); err != nil {
w.WriteHeader(http.StatusInternalServerError)
logger.Errorf(err.Error())
fmt.Fprintf(w, err.Error())
}
}
func (h *Handler) handle(w http.ResponseWriter, r *http.Request) error {
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}
l := RequestSummary{
Time: time.Now(),
Method: r.Method,
Path: r.URL.Path,
IsTLS: r.TLS != nil,
Body: string(body),
Header: r.Header,
Protocol: r.Proto,
}
switch h.format {
case "json":
s, err := l.formatJSON()
if err != nil {
return err
}
fmt.Println(s)
break
case "simple":
s := l.formatSimple()
logger.Printf(s)
break
default:
s := l.formatSimpleColor()
logger.Printf(s)
break
}
fmt.Fprintf(w, "OK")
return nil
}
func (rl RequestSummary) formatSimple() string {
return fmt.Sprintf("%s %s %s %s", rl.Method, rl.Path, rl.Protocol, rl.Body)
}
func (rl RequestSummary) formatSimpleColor() string {
return fmt.Sprintf("%s %s %s %s", color.GreenString(rl.Method), rl.Path, rl.Protocol, rl.Body)
}
func (rl RequestSummary) formatJSON() (string, error) {
logBuf := bytes.NewBuffer(nil)
enc := json.NewEncoder(logBuf)
if err := enc.Encode(rl); err != nil {
return "", err
}
return logBuf.String(), nil
}