Skip to content

Commit

Permalink
slightly more useful user agent (#762)
Browse files Browse the repository at this point in the history
* slightly more useful user agent
  • Loading branch information
willscott committed Oct 21, 2020
1 parent 7717801 commit ead2bc9
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions client/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"encoding/hex"
"fmt"
nhttp "net/http"
"os"
"path"
"strings"
"time"

Expand All @@ -21,6 +23,8 @@ import (

var errClientClosed = fmt.Errorf("client closed")

const defaultClientExec = "unknown"

// New creates a new client pointing to an HTTP endpoint
func New(url string, chainHash []byte, transport nhttp.RoundTripper) (client.Client, error) {
if transport == nil {
Expand All @@ -29,10 +33,16 @@ func New(url string, chainHash []byte, transport nhttp.RoundTripper) (client.Cli
if !strings.HasSuffix(url, "/") {
url += "/"
}
pn, err := os.Executable()
if err != nil {
pn = defaultClientExec
}
agent := fmt.Sprintf("drand-client-%s/1.0", path.Base(pn))
c := &httpClient{
root: url,
client: instrumentClient(url, transport),
l: log.DefaultLogger(),
Agent: agent,
done: make(chan struct{}),
}
chainInfo, err := c.FetchChainInfo(chainHash)
Expand All @@ -53,11 +63,17 @@ func NewWithInfo(url string, info *chain.Info, transport nhttp.RoundTripper) (cl
url += "/"
}

pn, err := os.Executable()
if err != nil {
pn = defaultClientExec
}
agent := fmt.Sprintf("drand-client-%s/1.0", path.Base(pn))
c := &httpClient{
root: url,
chainInfo: info,
client: instrumentClient(url, transport),
l: log.DefaultLogger(),
Agent: agent,
done: make(chan struct{}),
}
return c, nil
Expand Down Expand Up @@ -132,6 +148,7 @@ func instrumentClient(url string, transport nhttp.RoundTripper) *nhttp.Client {
type httpClient struct {
root string
client *nhttp.Client
Agent string
chainInfo *chain.Info
l log.Logger
done chan struct{}
Expand All @@ -142,6 +159,11 @@ func (h *httpClient) SetLog(l log.Logger) {
h.l = l
}

// SetUserAgent sets the user agent used by the client
func (h *httpClient) SetUserAgent(ua string) {
h.Agent = ua
}

// String returns the name of this client.
func (h *httpClient) String() string {
return fmt.Sprintf("HTTP(%q)", h.root)
Expand Down Expand Up @@ -170,6 +192,7 @@ func (h *httpClient) FetchChainInfo(chainHash []byte) (*chain.Info, error) {
resC <- httpInfoResponse{nil, fmt.Errorf("creating request: %w", err)}
return
}
req.Header.Set("User-Agent", h.Agent)

infoBody, err := h.client.Do(req)
if err != nil {
Expand Down Expand Up @@ -240,6 +263,7 @@ func (h *httpClient) Get(ctx context.Context, round uint64) (client.Result, erro
resC <- httpGetResponse{nil, fmt.Errorf("creating request: %w", err)}
return
}
req.Header.Set("User-Agent", h.Agent)

randResponse, err := h.client.Do(req)
if err != nil {
Expand Down

0 comments on commit ead2bc9

Please sign in to comment.