-
Notifications
You must be signed in to change notification settings - Fork 17
/
ethclient.go
100 lines (89 loc) · 2.13 KB
/
ethclient.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
97
98
99
100
package main
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/ethereum/go-ethereum/rpc"
)
type ethclientHandler struct {
rpc *rpc.Client
logFile *os.File
transport *loggingRoundTrip
}
func newEthclientHandler(addr string) (*ethclientHandler, error) {
rt := &loggingRoundTrip{
inner: http.DefaultTransport,
}
httpClient := rpc.WithHTTPClient(&http.Client{Transport: rt})
ctx := context.Background()
rpcClient, err := rpc.DialOptions(ctx, addr, httpClient)
if err != nil {
return nil, err
}
return ðclientHandler{
rpc: rpcClient,
logFile: nil,
transport: rt,
}, nil
}
func (l *ethclientHandler) RotateLog(filename string) error {
if l.logFile != nil {
if err := l.logFile.Close(); err != nil {
return err
}
}
f, err := os.Create(filename)
if err != nil {
return err
}
l.logFile = f
l.transport.w = f
return nil
}
// WriteComment adds the given text as a comment to the current log file.
func (l *ethclientHandler) WriteComment(text string) error {
text = strings.TrimSpace(text)
text = "// " + strings.Replace(text, "\n", "\n// ", -1) + "\n"
_, err := io.WriteString(l.logFile, text)
return err
}
func (l *ethclientHandler) Close() {
if l.logFile != nil {
l.logFile.Close()
}
}
// loggingRoundTrip writes requests and responses to the test log.
type loggingRoundTrip struct {
w io.Writer
inner http.RoundTripper
}
func (rt *loggingRoundTrip) RoundTrip(req *http.Request) (*http.Response, error) {
// Read and log the request body.
reqBytes, err := io.ReadAll(req.Body)
req.Body.Close()
if err != nil {
return nil, err
}
fmt.Fprintf(rt.w, ">> %s\n", bytes.TrimSpace(reqBytes))
reqCopy := *req
reqCopy.Body = io.NopCloser(bytes.NewReader(reqBytes))
// Do the round trip.
resp, err := rt.inner.RoundTrip(&reqCopy)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Read and log the response bytes.
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
respCopy := *resp
respCopy.Body = io.NopCloser(bytes.NewReader(respBytes))
fmt.Fprintf(rt.w, "<< %s\n", bytes.TrimSpace(respBytes))
return &respCopy, nil
}