Skip to content

Commit

Permalink
request: permit using no auth
Browse files Browse the repository at this point in the history
  • Loading branch information
GiedriusS committed Nov 18, 2021
1 parent 6856e18 commit e7b85bb
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions rest-request.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,23 @@ type StatusMessage struct {

// NewClient initializes client for interacting with an instance of Grafana server;
// apiKeyOrBasicAuth accepts either 'username:password' basic authentication credentials,
// or a Grafana API key
// or a Grafana API key. If it is an empty string then no authentication is used.
func NewClient(apiURL, apiKeyOrBasicAuth string, client *http.Client) (*Client, error) {
key := ""
basicAuth := strings.Contains(apiKeyOrBasicAuth, ":")
baseURL, err := url.Parse(apiURL)
if err != nil {
return nil, err
}
if !basicAuth {
key = fmt.Sprintf("Bearer %s", apiKeyOrBasicAuth)
} else {
parts := strings.Split(apiKeyOrBasicAuth, ":")
baseURL.User = url.UserPassword(parts[0], parts[1])
if len(apiKeyOrBasicAuth) > 0 {
if !basicAuth {
key = fmt.Sprintf("Bearer %s", apiKeyOrBasicAuth)
} else {
parts := strings.Split(apiKeyOrBasicAuth, ":")
baseURL.User = url.UserPassword(parts[0], parts[1])
}
}

return &Client{baseURL: baseURL.String(), basicAuth: basicAuth, key: key, client: client}, nil
}

Expand Down Expand Up @@ -105,7 +108,7 @@ func (r *Client) doRequest(ctx context.Context, method, query string, params url
return nil, 0, err
}
req = req.WithContext(ctx)
if !r.basicAuth {
if !r.basicAuth && len(r.key) > 0 {
req.Header.Set("Authorization", r.key)
}
req.Header.Set("Accept", "application/json")
Expand Down

0 comments on commit e7b85bb

Please sign in to comment.