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

Commit 80e79a9

Browse files
Add WithOrgID function to Grafana client (#130)
* Add `WithOrgID` function to Grafana client Issue: grafana/terraform-provider-grafana#747 This will allow the Terraform provider to use a different Org ID for each resource. Currently, the client is configured once for each `provider` block One caveat is that this feature can only be used with basic auth since API keys are org-scoped * Fix linting
1 parent 0e0d9a2 commit 80e79a9

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

client.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ type Config struct {
3434
HTTPHeaders map[string]string
3535
// Client provides an optional HTTP client, otherwise a default will be used.
3636
Client *http.Client
37-
// OrgID provides an optional organization ID, ignored when using APIKey, BasicAuth defaults to last used org
37+
// OrgID provides an optional organization ID
38+
// with BasicAuth, it defaults to last used org
39+
// with APIKey, it is disallowed because API keys are scoped to a single org
3840
OrgID int64
3941
// NumRetries contains the number of attempted retries
4042
NumRetries int
@@ -63,6 +65,12 @@ func New(baseURL string, cfg Config) (*Client, error) {
6365
}, nil
6466
}
6567

68+
// WithOrgID returns a new client with the provided organization ID.
69+
func (c Client) WithOrgID(orgID int64) *Client {
70+
c.config.OrgID = orgID
71+
return &c
72+
}
73+
6674
func (c *Client) request(method, requestPath string, query url.Values, body io.Reader, responseStruct interface{}) error {
6775
var (
6876
req *http.Request
@@ -153,10 +161,14 @@ func (c *Client) newRequest(method, requestPath string, query url.Values, body i
153161
}
154162

155163
if c.config.APIKey != "" {
164+
if c.config.OrgID != 0 {
165+
return req, fmt.Errorf("cannot use both API key and org ID. API keys are scoped to single org")
166+
}
156167
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.config.APIKey))
157168
} else if c.config.OrgID != 0 {
158169
req.Header.Add("X-Grafana-Org-Id", strconv.FormatInt(c.config.OrgID, 10))
159170
}
171+
160172
if c.config.HTTPHeaders != nil {
161173
for k, v := range c.config.HTTPHeaders {
162174
req.Header.Add(k, v)

0 commit comments

Comments
 (0)