2024-06-22 15:37:15 +00:00
|
|
|
package jsonrpc2
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2024-11-18 21:25:49 +00:00
|
|
|
"errors"
|
2024-06-22 15:37:15 +00:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2024-06-23 12:37:10 +00:00
|
|
|
"net/url"
|
|
|
|
|
|
|
|
"github.com/tv42/httpunix"
|
2024-06-22 15:37:15 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type httpClient struct {
|
|
|
|
c *http.Client
|
|
|
|
url string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewHTTPClient returns a Client which will use HTTP POST requests against the
|
|
|
|
// given URL as a transport for JSONRPC2 method calls.
|
2024-06-23 12:37:10 +00:00
|
|
|
func NewHTTPClient(urlStr string) Client {
|
2024-06-22 15:37:15 +00:00
|
|
|
return &httpClient{
|
|
|
|
c: &http.Client{
|
|
|
|
Transport: http.DefaultTransport.(*http.Transport).Clone(),
|
|
|
|
},
|
2024-06-23 12:37:10 +00:00
|
|
|
url: urlStr,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewUnixHTTPClient returns a Client which will use HTTP POST requests against
|
|
|
|
// the given unix socket as a transport for JSONRPC2 method calls. The given
|
|
|
|
// path will be used as the path portion of the HTTP request.
|
|
|
|
func NewUnixHTTPClient(unixSocketPath, reqPath string) Client {
|
|
|
|
const host = "uds"
|
|
|
|
|
|
|
|
u := &url.URL{
|
|
|
|
Scheme: httpunix.Scheme,
|
|
|
|
Host: host,
|
|
|
|
Path: reqPath,
|
|
|
|
}
|
|
|
|
|
|
|
|
transport := new(httpunix.Transport)
|
|
|
|
transport.RegisterLocation(host, unixSocketPath)
|
|
|
|
|
|
|
|
return &httpClient{
|
|
|
|
c: &http.Client{Transport: transport},
|
|
|
|
url: u.String(),
|
2024-06-22 15:37:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *httpClient) Call(
|
2024-09-23 17:04:14 +00:00
|
|
|
ctx context.Context, rcv any, method string, args ...any,
|
2024-06-22 15:37:15 +00:00
|
|
|
) error {
|
|
|
|
var (
|
|
|
|
body = new(bytes.Buffer)
|
|
|
|
enc = json.NewEncoder(body)
|
|
|
|
)
|
|
|
|
|
2024-09-23 17:04:14 +00:00
|
|
|
id, err := encodeRequest(ctx, enc, method, args)
|
2024-06-22 15:37:15 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("encoding request: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "POST", c.url, body)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("constructing POST request to %q: %w", c.url, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
res, err := c.c.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("performing request: %w", err)
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
|
|
|
dec := json.NewDecoder(res.Body)
|
|
|
|
|
|
|
|
resID, err := decodeResponse(dec, rcv)
|
2024-11-18 21:25:49 +00:00
|
|
|
if errors.As(err, new(Error)) {
|
|
|
|
return err
|
|
|
|
} else if err != nil {
|
2024-06-22 15:37:15 +00:00
|
|
|
return fmt.Errorf("decoding response: %w", err)
|
|
|
|
} else if resID != id {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"expected response with ID %q, got %q", id, resID,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|