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 authored and wurbanski committed Mar 30, 2022
1 parent 39c30e3 commit e21f794
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 @@ -88,20 +88,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 @@ -143,7 +146,7 @@ func (r *Client) doRequest(ctx context.Context, method, query, rawPath string, p
return nil, 0, err
}
req = req.WithContext(ctx)
if !r.basicAuth {
if !r.basicAuth && len(r.key) > 0 {
req.Header.Set("Authorization", r.key)
}
if r.customHeaders != nil {
Expand Down

0 comments on commit e21f794

Please sign in to comment.