forked from s1na/rpctestgen
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ethclient.go
96 lines (86 loc) · 2.02 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
package main
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"os"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/ethclient/gethclient"
"github.com/ethereum/go-ethereum/rpc"
)
type ethclientHandler struct {
ethclient *ethclient.Client
gethclient *gethclient.Client
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{
ethclient.NewClient(rpcClient),
gethclient.New(rpcClient),
rpcClient,
nil,
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
}
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
}