Browse Source

Merge pull request #9 from abhinav/v2

Add NewClientWith constructor
Matt Baer 11 months ago
parent
commit
68cbee8f4a
No account linked to committer's email
1 changed files with 36 additions and 12 deletions
  1. 36
    12
      writeas.go

+ 36
- 12
writeas.go View File

@@ -44,31 +44,55 @@ const defaultHTTPTimeout = 10 * time.Second
44 44
 //     c := writeas.NewClient()
45 45
 //     c.SetToken("00000000-0000-0000-0000-000000000000")
46 46
 func NewClient() *Client {
47
-	return &Client{
48
-		client:  &http.Client{Timeout: defaultHTTPTimeout},
49
-		baseURL: apiURL,
50
-	}
47
+	return NewClientWith(Config{URL: apiURL})
51 48
 }
52 49
 
53 50
 // NewTorClient creates a new API client for communicating with the Write.as
54 51
 // Tor hidden service, using the given port to connect to the local SOCKS
55 52
 // proxy.
56 53
 func NewTorClient(port int) *Client {
57
-	dialSocksProxy := socks.DialSocksProxy(socks.SOCKS5, fmt.Sprintf("127.0.0.1:%d", port))
58
-	transport := &http.Transport{Dial: dialSocksProxy}
59
-	return &Client{
60
-		client:  &http.Client{Transport: transport},
61
-		baseURL: torAPIURL,
62
-	}
54
+	return NewClientWith(Config{URL: torAPIURL, TorPort: port})
63 55
 }
64 56
 
65 57
 // NewDevClient creates a new API client for development and testing. It'll
66 58
 // communicate with our development servers, and SHOULD NOT be used in
67 59
 // production.
68 60
 func NewDevClient() *Client {
61
+	return NewClientWith(Config{URL: devAPIURL})
62
+}
63
+
64
+// Config configures a Write.as client.
65
+type Config struct {
66
+	// URL of the Write.as API service. Defaults to https://write.as/api.
67
+	URL string
68
+
69
+	// If specified, the API client will communicate with the Write.as Tor
70
+	// hidden service using the provided port to connect to the local SOCKS
71
+	// proxy.
72
+	TorPort int
73
+
74
+	// If specified, requests will be authenticated using this user token.
75
+	// This may be provided after making a few anonymous requests with
76
+	// SetToken.
77
+	Token string
78
+}
79
+
80
+// NewClientWith builds a new API client with the provided configuration.
81
+func NewClientWith(c Config) *Client {
82
+	if c.URL == "" {
83
+		c.URL = apiURL
84
+	}
85
+
86
+	httpClient := &http.Client{Timeout: defaultHTTPTimeout}
87
+	if c.TorPort > 0 {
88
+		dialSocksProxy := socks.DialSocksProxy(socks.SOCKS5, fmt.Sprintf("127.0.0.1:%d", c.TorPort))
89
+		httpClient.Transport = &http.Transport{Dial: dialSocksProxy}
90
+	}
91
+
69 92
 	return &Client{
70
-		client:  &http.Client{Timeout: defaultHTTPTimeout},
71
-		baseURL: devAPIURL,
93
+		client:  httpClient,
94
+		baseURL: c.URL,
95
+		token:   c.Token,
72 96
 	}
73 97
 }
74 98