Set HTTP client via option. Update readme, Makefile, go.sum

Signed-off-by: Vartan Benohanian <vartanbeno@gmail.com>
This commit is contained in:
Vartan Benohanian
2020-08-26 23:13:34 -04:00
parent e1ce8a7a14
commit c0f0cf8be6
12 changed files with 90 additions and 58 deletions
+13 -7
View File
@@ -1,6 +1,8 @@
package reddit
import (
"errors"
"net/http"
"net/url"
"os"
)
@@ -8,8 +10,18 @@ import (
// Opt is a configuration option to initialize a client.
type Opt func(*Client) error
// WithHTTPClient sets the HTTP client which will be used to make requests.
func WithHTTPClient(httpClient *http.Client) Opt {
return func(c *Client) error {
if httpClient == nil {
return errors.New("httpClient: cannot be nil")
}
c.client = httpClient
return nil
}
}
// FromEnv configures the client with values from environment variables.
//
// Supported environment variables:
// GO_REDDIT_CLIENT_ID to set the client's id.
// GO_REDDIT_CLIENT_SECRET to set the client's secret.
@@ -19,19 +31,15 @@ func FromEnv(c *Client) error {
if v := os.Getenv("GO_REDDIT_CLIENT_ID"); v != "" {
c.ID = v
}
if v := os.Getenv("GO_REDDIT_CLIENT_SECRET"); v != "" {
c.Secret = v
}
if v := os.Getenv("GO_REDDIT_CLIENT_USERNAME"); v != "" {
c.Username = v
}
if v := os.Getenv("GO_REDDIT_CLIENT_PASSWORD"); v != "" {
c.Password = v
}
return nil
}
@@ -42,7 +50,6 @@ func WithBaseURL(u string) Opt {
if err != nil {
return err
}
c.BaseURL = url
return nil
}
@@ -55,7 +62,6 @@ func WithTokenURL(u string) Opt {
if err != nil {
return err
}
c.TokenURL = url
return nil
}
+23 -3
View File
@@ -1,12 +1,22 @@
package reddit
import (
"net/http"
"net/url"
"os"
"testing"
"github.com/stretchr/testify/require"
)
func TestWithHTTPClient(t *testing.T) {
_, err := NewClient(nil, WithHTTPClient(nil))
require.EqualError(t, err, "httpClient: cannot be nil")
_, err = NewClient(nil, WithHTTPClient(&http.Client{}))
require.NoError(t, err)
}
func TestFromEnv(t *testing.T) {
os.Setenv("GO_REDDIT_CLIENT_ID", "id1")
defer os.Unsetenv("GO_REDDIT_CLIENT_ID")
@@ -20,7 +30,7 @@ func TestFromEnv(t *testing.T) {
os.Setenv("GO_REDDIT_CLIENT_PASSWORD", "password1")
defer os.Unsetenv("GO_REDDIT_CLIENT_PASSWORD")
c, err := NewClient(nil, nil, FromEnv)
c, err := NewClient(nil, FromEnv)
require.NoError(t, err)
type values struct {
@@ -33,15 +43,25 @@ func TestFromEnv(t *testing.T) {
}
func TestWithBaseURL(t *testing.T) {
c, err := NewClient(nil, WithBaseURL(":"))
urlErr, ok := err.(*url.Error)
require.True(t, ok)
require.Equal(t, "parse", urlErr.Op)
baseURL := "http://localhost:8080"
c, err := NewClient(nil, nil, WithBaseURL(baseURL))
c, err = NewClient(nil, WithBaseURL(baseURL))
require.NoError(t, err)
require.Equal(t, baseURL, c.BaseURL.String())
}
func TestWithTokenURL(t *testing.T) {
c, err := NewClient(nil, WithTokenURL(":"))
urlErr, ok := err.(*url.Error)
require.True(t, ok)
require.Equal(t, "parse", urlErr.Op)
tokenURL := "http://localhost:8080/api/v1/access_token"
c, err := NewClient(nil, nil, WithTokenURL(tokenURL))
c, err = NewClient(nil, WithTokenURL(tokenURL))
require.NoError(t, err)
require.Equal(t, tokenURL, c.TokenURL.String())
}
+28 -27
View File
@@ -124,32 +124,11 @@ func (c *Client) OnRequestCompleted(rc RequestCompletionCallback) {
c.onRequestCompleted = rc
}
func newClient(httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = &http.Client{}
}
// todo...
// Some endpoints (notably the ones to get random subreddits/posts) redirect to a
// reddit.com url, which returns a 403 Forbidden for some reason, unless the url's
// host is changed to oauth.reddit.com
httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
redirectURL := req.URL.String()
redirectURL = strings.Replace(redirectURL, "https://www.reddit.com", defaultBaseURL, 1)
reqURL, err := url.Parse(redirectURL)
if err != nil {
return err
}
req.URL = reqURL
return nil
}
func newClient() *Client {
baseURL, _ := url.Parse(defaultBaseURL)
tokenURL, _ := url.Parse(defaultTokenURL)
client := &Client{client: httpClient, BaseURL: baseURL, TokenURL: tokenURL}
client := &Client{BaseURL: baseURL, TokenURL: tokenURL}
client.Account = &AccountService{client: client}
client.Collection = &CollectionService{client: client}
@@ -171,10 +150,9 @@ func newClient(httpClient *http.Client) *Client {
return client
}
// NewClient returns a new Reddit API client. If a nil httpClient is provided,
// a new http.Client will be used.
func NewClient(httpClient *http.Client, creds *Credentials, opts ...Opt) (*Client, error) {
client := newClient(httpClient)
// NewClient returns a new Reddit API client.
func NewClient(creds *Credentials, opts ...Opt) (*Client, error) {
client := newClient()
for _, opt := range opts {
if err := opt(client); err != nil {
@@ -182,6 +160,29 @@ func NewClient(httpClient *http.Client, creds *Credentials, opts ...Opt) (*Clien
}
}
if client.client == nil {
client.client = &http.Client{}
}
// todo...
// Some endpoints (notably the ones to get random subreddits/posts) redirect to a
// reddit.com url, which returns a 403 Forbidden for some reason, unless the url's
// host is changed to oauth.reddit.com
if client.client.CheckRedirect == nil {
client.client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
redirectURL := req.URL.String()
redirectURL = strings.Replace(redirectURL, "https://www.reddit.com", defaultBaseURL, 1)
reqURL, err := url.Parse(redirectURL)
if err != nil {
return err
}
req.URL = reqURL
return nil
}
}
if creds != nil {
client.ID = creds.ID
client.Secret = creds.Secret
+3 -3
View File
@@ -31,7 +31,7 @@ func setup() (*Client, *http.ServeMux, func()) {
fmt.Fprint(w, response)
})
client, _ := NewClient(nil,
client, _ := NewClient(
&Credentials{"id1", "secret1", "user1", "password1"},
WithBaseURL(server.URL),
WithTokenURL(server.URL+"/api/v1/access_token"),
@@ -92,7 +92,7 @@ func testClientDefaults(t *testing.T, c *Client) {
}
func TestNewClient(t *testing.T) {
c, err := NewClient(nil, nil)
c, err := NewClient(nil)
require.NoError(t, err)
testClientDefaults(t, c)
}
@@ -102,7 +102,7 @@ func TestNewClient_Error(t *testing.T) {
return errors.New("foo")
}
_, err := NewClient(nil, nil, errorOpt)
_, err := NewClient(nil, errorOpt)
require.EqualError(t, err, "foo")
}