add recorder for serial handler

This commit is contained in:
ginuerzh
2023-09-18 21:13:11 +08:00
parent a623232cc1
commit a743862f23
9 changed files with 188 additions and 26 deletions

62
recorder/http.go Normal file
View File

@ -0,0 +1,62 @@
package recorder
import (
"bytes"
"context"
"fmt"
"net/http"
"time"
"github.com/go-gost/core/recorder"
)
type httpRecorderOptions struct {
timeout time.Duration
}
type HTTPRecorderOption func(opts *httpRecorderOptions)
func TimeoutHTTPRecorderOption(timeout time.Duration) HTTPRecorderOption {
return func(opts *httpRecorderOptions) {
opts.timeout = timeout
}
}
type httpRecorder struct {
url string
httpClient *http.Client
}
// HTTPRecorder records data to HTTP service.
func HTTPRecorder(url string, opts ...HTTPRecorderOption) recorder.Recorder {
var options httpRecorderOptions
for _, opt := range opts {
opt(&options)
}
return &httpRecorder{
url: url,
httpClient: &http.Client{
Timeout: options.timeout,
},
}
}
func (r *httpRecorder) Record(ctx context.Context, b []byte) error {
req, err := http.NewRequest(http.MethodPost, r.url, bytes.NewReader(b))
if err != nil {
return err
}
resp, err := r.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%d %s", resp.StatusCode, resp.Status)
}
return nil
}

52
recorder/tcp.go Normal file
View File

@ -0,0 +1,52 @@
package recorder
import (
"context"
"net"
"time"
"github.com/go-gost/core/recorder"
)
type tcpRecorderOptions struct {
timeout time.Duration
}
type TCPRecorderOption func(opts *tcpRecorderOptions)
func TimeoutTCPRecorderOption(timeout time.Duration) TCPRecorderOption {
return func(opts *tcpRecorderOptions) {
opts.timeout = timeout
}
}
type tcpRecorder struct {
addr string
dialer *net.Dialer
}
// TCPRecorder records data to TCP service.
func TCPRecorder(addr string, opts ...TCPRecorderOption) recorder.Recorder {
var options tcpRecorderOptions
for _, opt := range opts {
opt(&options)
}
return &tcpRecorder{
addr: addr,
dialer: &net.Dialer{
Timeout: options.timeout,
},
}
}
func (r *tcpRecorder) Record(ctx context.Context, b []byte) error {
c, err := r.dialer.DialContext(ctx, "tcp", r.addr)
if err != nil {
return err
}
defer c.Close()
_, err = c.Write(b)
return err
}