From ebb560a33643019078aad4c4ae8db46681c4e702 Mon Sep 17 00:00:00 2001 From: medains Date: Wed, 5 Aug 2020 09:29:58 +0100 Subject: [PATCH] Add organization ID to client connection using header. This seems like the right place to do so - the resource API calls that require an organization ID that are not-quite RESTful also would need authentication with a user that is an administrator for the organization. So putting it in at this level works out, and also avoids adding orgID parameters all over the place. Co-authored-by: hansnqyr --- client.go | 7 ++++++- client_test.go | 6 +++--- mock.go | 2 +- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/client.go b/client.go index 370e020..5f2f3c5 100644 --- a/client.go +++ b/client.go @@ -20,12 +20,13 @@ import ( type Client struct { key string baseURL url.URL + orgID string *http.Client } //New creates a new grafana client //auth can be in user:pass format, or it can be an api key -func New(auth, baseURL string) (*Client, error) { +func New(auth, baseURL string, orgID int) (*Client, error) { u, err := url.Parse(baseURL) if err != nil { return nil, err @@ -40,6 +41,7 @@ func New(auth, baseURL string) (*Client, error) { return &Client{ key, *u, + fmt.Sprintf("%d", orgID), cleanhttp.DefaultClient(), }, nil } @@ -88,6 +90,9 @@ func (c *Client) newRequest(method, requestPath string, query url.Values, body i if err != nil { return req, err } + + req.Header.Add("X-Grafana-Org-Id", c.orgID) + if c.key != "" { req.Header.Add("Authorization", c.key) } diff --git a/client_test.go b/client_test.go index 0e1da90..ce982e9 100644 --- a/client_test.go +++ b/client_test.go @@ -8,7 +8,7 @@ import ( ) func TestNew_basicAuth(t *testing.T) { - c, err := New("user:pass", "http://my-grafana.com") + c, err := New("user:pass", "http://my-grafana.com", 1) if err != nil { t.Errorf("expected error to be nil; got: %s", err.Error()) } @@ -20,7 +20,7 @@ func TestNew_basicAuth(t *testing.T) { } func TestNew_tokenAuth(t *testing.T) { - c, err := New("123", "http://my-grafana.com") + c, err := New("123", "http://my-grafana.com", 1) if err != nil { t.Errorf("expected error to be nil; got: %s", err.Error()) } @@ -37,7 +37,7 @@ func TestNew_tokenAuth(t *testing.T) { } func TestNew_invalidURL(t *testing.T) { - _, err := New("123", "://my-grafana.com") + _, err := New("123", "://my-grafana.com", 1) expected := "parse \"://my-grafana.com\": missing protocol scheme" if err.Error() != expected { diff --git a/mock.go b/mock.go index 607e27d..a5cef0a 100644 --- a/mock.go +++ b/mock.go @@ -40,6 +40,6 @@ func gapiTestTools(code int, body string) (*mockServer, *Client) { Host: "my-grafana.com", } - client := &Client{"my-key", url, httpClient} + client := &Client{"my-key", url, "1", httpClient} return mock, client }