-
Notifications
You must be signed in to change notification settings - Fork 946
/
main.go
81 lines (74 loc) · 1.89 KB
/
main.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
// Package main implements a simple, http-request-sink which writes
// incoming http request bodies to an append-only text file at a specified directory.
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"time"
"github.com/prysmaticlabs/prysm/v4/config/params"
)
func main() {
port := flag.Int("port", 8080, "port to listen on")
writeDirPath := flag.String("write-dir", "", "directory to write an append-only file")
flag.Parse()
if *writeDirPath == "" {
log.Fatal("Needs a -write-dir path")
}
// If the file doesn't exist, create it, or append to the file.
f, err := os.OpenFile(
filepath.Join(*writeDirPath, "requests.log"),
os.O_APPEND|os.O_CREATE|os.O_RDWR,
params.BeaconIoConfig().ReadWritePermissions,
)
if err != nil {
log.Println(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
http.HandleFunc("/", func(writer http.ResponseWriter, r *http.Request) {
reqContent := map[string]interface{}{}
if err = parseRequest(r, &reqContent); err != nil {
log.Println(err)
}
log.Printf("Capturing request from %s", r.RemoteAddr)
if err = captureRequest(f, reqContent); err != nil {
log.Println(err)
}
})
log.Printf("Listening on port %d", *port)
srv := &http.Server{
Addr: ":" + strconv.Itoa(*port),
ReadHeaderTimeout: 3 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
func captureRequest(f *os.File, m map[string]interface{}) error {
enc, err := json.Marshal(m)
if err != nil {
return err
}
_, err = f.WriteString(fmt.Sprintf("%s\n", enc))
return err
}
func parseRequest(req *http.Request, unmarshalStruct interface{}) error {
body, err := io.ReadAll(req.Body)
if err != nil {
return err
}
if err = req.Body.Close(); err != nil {
return err
}
req.Body = io.NopCloser(bytes.NewBuffer(body))
return json.Unmarshal(body, unmarshalStruct)
}