-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
149 lines (117 loc) · 4.13 KB
/
middleware.go
File metadata and controls
149 lines (117 loc) · 4.13 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
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
package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"slices"
"strings"
)
func MiddlewareLog(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(">>> Incoming request: ", r.Method, r.RequestURI)
var buf bytes.Buffer
buf.WriteString("\n")
buf.WriteString("==================================================\n")
buf.WriteString(fmt.Sprintf("[%s] %s", r.Method, r.RequestURI) + "\n")
buf.WriteString("==================================================\n")
contentType := r.Header.Get("Content-Type")
if contentType == "" {
contentType = "[null]" // Default content type if not set
}
// Log headers
buf.WriteString("Headers\n")
buf.WriteString("--------------------------------------------------\n")
for name, values := range r.Header {
for _, val := range values {
buf.WriteString(fmt.Sprintf("%v: %v", name, val) + "\n")
}
}
buf.WriteString("--------------------------------------------------\n")
buf.WriteString("\n")
buf.WriteString("Body\n")
buf.WriteString("--------------------------------------------------\n")
if r.Body == nil || r.Body == http.NoBody {
buf.WriteString("[null]\n")
} else {
// check if the content type is multipart/form-data
if strings.HasPrefix(contentType, "multipart/form-data") {
// Parse the multipart form data
err := r.ParseMultipartForm(32 << 20) // 32MB max memory
if err != nil {
log.Fatalf("Error parsing multipart form: %v", err)
http.Error(w, "Error parsing multipart form", http.StatusInternalServerError)
return
}
// Log the form values
if r.MultipartForm.Value != nil {
for key, values := range r.MultipartForm.Value {
for _, value := range values {
buf.WriteString(fmt.Sprintf("Form Field: %s, Value: %s", key, value) + "\n")
}
}
}
// Log the file uploads
if r.MultipartForm != nil && r.MultipartForm.File != nil {
for key := range r.MultipartForm.File {
files := r.MultipartForm.File[key]
for _, fileHeader := range files {
buf.WriteString(fmt.Sprintf("Form Field: %s, FileName: %s, Content-Type: %s", key, fileHeader.Filename, fileHeader.Header.Get("Content-Type")) + "\n")
}
}
}
} else {
var allowedPrintBody = []string{"application/x-www-form-urlencoded",
"application/javascript",
"application/json",
"application/xml",
"text/plain",
"text/html",
"text/csv",
"text/xml"}
if slices.Contains(allowedPrintBody, contentType) {
// Read and log body
body, err := io.ReadAll(r.Body)
if err != nil {
log.Panicf("Error reading body: %v", err)
http.Error(w, "can't read body", http.StatusBadRequest)
return
}
defer r.Body.Close() // Close the body
r.Body = io.NopCloser(bytes.NewBuffer(body))
detectedContentType, readBytes, err := detectContentType(&r.Body)
if err != nil {
http.Error(w, "Failed to read body", http.StatusInternalServerError)
return
}
if slices.Contains(allowedPrintBody, detectedContentType) {
buf.WriteString(fmt.Sprintf("%v", string(body)) + "\n")
} else {
buf.WriteString("Body not logged due to unsupported content type: " + detectedContentType + "\n")
}
// Restore the body with the read bytes included
r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(readBytes), r.Body))
} else {
buf.WriteString("Body not logged due to unsupported content type: " + contentType + "\n")
}
}
}
buf.WriteString("--------------------------------------------------\n")
log.Println(buf.String())
next.ServeHTTP(w, r)
})
}
// detectContentType reads a sample from the request body and detects its content type
func detectContentType(body *io.ReadCloser) (string, []byte, error) {
buf2 := make([]byte, 512)
n, err := (*body).Read(buf2)
if err != nil && err != io.EOF {
return "", nil, err
}
// Detect the content type
dcontentType := http.DetectContentType(buf2[:n])
dcontentType = strings.Split(dcontentType, ";")[0]
dcontentType = strings.ToLower(dcontentType)
return dcontentType, buf2[:n], nil
}