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
}