Merge pull request #8 from charlieegan3/set-client-base-url
Allow setting the baseURL of clients
This commit is contained in:
19
client.go
19
client.go
@@ -48,6 +48,25 @@ func (at *Client) SetRateLimit(customRateLimit int) {
|
||||
at.rateLimiter = time.Tick(time.Second / time.Duration(customRateLimit))
|
||||
}
|
||||
|
||||
func (at *Client) SetBaseURL(baseURL string) error {
|
||||
url, err := url.Parse(baseURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse baseURL: %s", err)
|
||||
}
|
||||
|
||||
if url.Scheme == "" {
|
||||
return fmt.Errorf("scheme of http or https must be specified")
|
||||
}
|
||||
|
||||
if url.Scheme != "https" && url.Scheme != "http" {
|
||||
return fmt.Errorf("http or https baseURL must be used")
|
||||
}
|
||||
|
||||
at.baseURL = url.String()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (at *Client) rateLimit() {
|
||||
<-at.rateLimiter
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -35,3 +36,48 @@ func TestClient_do(t *testing.T) {
|
||||
t.Errorf("there should be an error, but was nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SetBaseURL(t *testing.T) {
|
||||
testCases := []struct {
|
||||
description string
|
||||
url string
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
description: "accepts a valid URL",
|
||||
url: "http://localhost:3000",
|
||||
},
|
||||
{
|
||||
description: "accepts a valid HTTPS URL",
|
||||
url: "https://example.com",
|
||||
},
|
||||
{
|
||||
description: "rejects non http/https scheme url",
|
||||
url: "ftp://example.com",
|
||||
expectedError: "http or https baseURL must be used",
|
||||
},
|
||||
{
|
||||
description: "rejects url without scheme",
|
||||
url: "example.com",
|
||||
expectedError: "scheme of http or https must be specified",
|
||||
},
|
||||
}
|
||||
|
||||
c := testClient(t)
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.description, func(t *testing.T) {
|
||||
err := c.SetBaseURL(testCase.url)
|
||||
|
||||
if err != nil {
|
||||
if testCase.expectedError != "" {
|
||||
if !strings.Contains(err.Error(), testCase.expectedError) {
|
||||
t.Fatalf("unexpected error: %s", err)
|
||||
}
|
||||
} else {
|
||||
t.Fatalf("unexpected error: %s", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user