Skip to content
This repository has been archived by the owner on Jan 15, 2024. It is now read-only.

Add organization ID to client connection using header #9

Merged
merged 4 commits into from
Oct 28, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net/url"
"os"
"path"
"strconv"

"github.com/hashicorp/go-cleanhttp"
)
Expand All @@ -30,6 +31,8 @@ type Config struct {
BasicAuth *url.Userinfo
// Client provides an optional HTTP client, otherwise a default will be used.
Client *http.Client
// OrgID provides an optional organization ID, ignored when using APIKey, BasicAuth defaults to last used org
OrgID int64
}

// New creates a new Grafana client.
Expand Down Expand Up @@ -103,6 +106,8 @@ func (c *Client) newRequest(method, requestPath string, query url.Values, body i

if c.config.APIKey != "" {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.config.APIKey))
} else if c.config.OrgID != 0 {
woodsaj marked this conversation as resolved.
Show resolved Hide resolved
req.Header.Add("X-Grafana-Org-Id", strconv.FormatInt(c.config.OrgID, 10))
}

if os.Getenv("GF_LOG") != "" {
Expand Down
17 changes: 17 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,23 @@ func TestNew_tokenAuth(t *testing.T) {
}
}

func TestNew_orgId(t *testing.T) {
aknuds1 marked this conversation as resolved.
Show resolved Hide resolved
const orgID = 456
c, err := New("http://my-grafana.com", Config{OrgID: orgID})
if err != nil {
t.Fatalf("expected error to be nil; got: %s", err.Error())
}

expected := "http://my-grafana.com"
if c.baseURL.String() != expected {
t.Errorf("expected error: %s; got: %s", expected, c.baseURL.String())
}

if c.config.OrgID != orgID {
t.Errorf("expected error: %d; got: %d", orgID, c.config.OrgID)
}
}

func TestNew_invalidURL(t *testing.T) {
_, err := New("://my-grafana.com", Config{APIKey: "123"})

Expand Down