@@ -21,10 +21,11 @@ import (
2121type (
2222 // Client type is used to perform actions against the Tailscale API.
2323 Client struct {
24- apiKey string
25- http * http.Client
26- baseURL * url.URL
27- tailnet string
24+ apiKey string
25+ http * http.Client
26+ baseURL * url.URL
27+ tailnet string
28+ userAgent string // empty string means Go's default value.
2829 }
2930
3031 // APIError type describes an error as returned by the Tailscale API.
4748const baseURL = "https://api.tailscale.com"
4849const contentType = "application/json"
4950const defaultHttpClientTimeout = time .Minute
51+ const defaultUserAgent = "tailscale-client-go"
5052
5153// NewClient returns a new instance of the Client type that will perform operations against a chosen tailnet and will
5254// provide the apiKey for authorization. Additional options can be provided, see ClientOption for more details.
@@ -65,8 +67,9 @@ func NewClient(apiKey, tailnet string, options ...ClientOption) (*Client, error)
6567 }
6668
6769 c := & Client {
68- baseURL : u ,
69- tailnet : tailnet ,
70+ baseURL : u ,
71+ tailnet : tailnet ,
72+ userAgent : defaultUserAgent ,
7073 }
7174
7275 if apiKey != "" {
@@ -122,6 +125,15 @@ func WithOAuthClientCredentials(clientID, clientSecret string, scopes []string)
122125 }
123126}
124127
128+ // WithUserAgent sets a custom User-Agent header in HTTP requests.
129+ // Passing an empty string will make the client use Go's default value.
130+ func WithUserAgent (ua string ) ClientOption {
131+ return func (c * Client ) error {
132+ c .userAgent = ua
133+ return nil
134+ }
135+ }
136+
125137// TODO: consider setting `headers` and `body` via opts to decrease the number of arguments.
126138func (c * Client ) buildRequest (ctx context.Context , method , uri string , headers map [string ]string , body interface {}) (* http.Request , error ) {
127139 u , err := c .baseURL .Parse (uri )
@@ -142,6 +154,10 @@ func (c *Client) buildRequest(ctx context.Context, method, uri string, headers m
142154 return nil , err
143155 }
144156
157+ if c .userAgent != "" {
158+ req .Header .Set ("User-Agent" , c .userAgent )
159+ }
160+
145161 for k , v := range headers {
146162 req .Header .Set (k , v )
147163 }
0 commit comments