Skip to content

Commit

Permalink
Add Client.UseURL(...) (#484)
Browse files Browse the repository at this point in the history
  • Loading branch information
lgarber-akamai authored Mar 28, 2024
1 parent d349cae commit 219f13b
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
33 changes: 33 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import (
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"

Expand Down Expand Up @@ -138,6 +140,37 @@ func (c *Client) OnBeforeRequest(m func(request *Request) error) {
})
}

// UseURL parses the individual components of the given API URL and configures the client
// accordingly. For example, a valid URL.
// For example:
//
// client.UseURL("https://api.test.linode.com/v4beta")
func (c *Client) UseURL(apiURL string) (*Client, error) {
parsedURL, err := url.Parse(apiURL)
if err != nil {
return nil, fmt.Errorf("failed to parse URL: %w", err)
}

// Create a new URL excluding the path to use as the base URL
baseURL := &url.URL{
Host: parsedURL.Host,
Scheme: parsedURL.Scheme,
}

c.SetBaseURL(baseURL.String())

versionMatches := regexp.MustCompile(`/v[a-zA-Z0-9]+`).FindAllString(parsedURL.Path, -1)

// Only set the version if a version is found in the URL, else use the default
if len(versionMatches) > 0 {
c.SetAPIVersion(
strings.Trim(versionMatches[len(versionMatches)-1], "/"),
)
}

return c, nil
}

// SetBaseURL sets the base URL of the Linode v4 API (https://api.linode.com/v4)
func (c *Client) SetBaseURL(baseURL string) *Client {
baseURLPath, _ := url.Parse(baseURL)
Expand Down
28 changes: 28 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,34 @@ func TestClient_NewFromEnvToken(t *testing.T) {
}
}

func TestClient_UseURL(t *testing.T) {
client := NewClient(nil)

if _, err := client.UseURL("https://api.test1.linode.com/"); err != nil {
t.Fatal(err)
}

if client.baseURL != "api.test1.linode.com" {
t.Fatalf("mismatched base url: %s", client.baseURL)
}

if client.apiVersion != "v4" {
t.Fatalf("mismatched api version: %s", client.apiVersion)
}

if _, err := client.UseURL("https://api.test2.linode.com/v4beta"); err != nil {
t.Fatal(err)
}

if client.baseURL != "api.test2.linode.com" {
t.Fatalf("mismatched base url: %s", client.baseURL)
}

if client.apiVersion != "v4beta" {
t.Fatalf("mismatched api version: %s", client.apiVersion)
}
}

const configNewFromEnv = `
[default]
api_url = api.cool.linode.com
Expand Down

0 comments on commit 219f13b

Please sign in to comment.