-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
80 lines (67 loc) · 1.83 KB
/
main.go
File metadata and controls
80 lines (67 loc) · 1.83 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
package main
import (
"encoding/base64"
"encoding/json"
"io"
"log"
"net/http"
"os"
"runtime/debug"
)
// Version is the application version, injected at build time via ldflags
var Version = "dev"
type LogEntry struct {
BodyBase64 string `json:"bodyBase64"`
Headers map[string]string `json:"headers"`
Path string `json:"path"` // Add path field
}
func handler(w http.ResponseWriter, r *http.Request) {
// Read the request body
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Unable to read request body", http.StatusInternalServerError)
return
}
// Base64 encode the body
bodyBase64 := base64.StdEncoding.EncodeToString(body)
// Collect headers into a map
headers := make(map[string]string)
for key, values := range r.Header {
headers[key] = values[0] // Take the first value for each header
}
// Create log entry
logEntry := LogEntry{
BodyBase64: bodyBase64,
Headers: headers,
Path: r.URL.Path, // Add path to log entry
}
// Serialize log entry to JSON
logJSON, err := json.Marshal(logEntry)
if err != nil {
http.Error(w, "Unable to create log entry", http.StatusInternalServerError)
return
}
// Log the JSON
log.Println(string(logJSON))
// Add application version to X-App-Version header
w.Header().Set("X-App-Version", Version)
// Respond to the client
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("OK\n"))
}
func main() {
// Set the build version from the build info if not set by the build system
if Version == "dev" || Version == "" {
if bi, ok := debug.ReadBuildInfo(); ok {
if bi.Main.Version != "" && bi.Main.Version != "(devel)" {
Version = bi.Main.Version
}
}
}
port := os.Getenv("PORT")
if port == "" {
port = "8080" // Default port if not specified
}
http.HandleFunc("/", handler)
http.ListenAndServe(":"+port, nil)
}