Go client for the Write.as API https://developers.write.as

writeas.go 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. // Package writeas provides the binding for the Write.as API
  2. package writeas
  3. import (
  4. "bytes"
  5. "code.as/core/socks"
  6. "encoding/json"
  7. "fmt"
  8. "github.com/writeas/impart"
  9. "io"
  10. "net/http"
  11. "time"
  12. )
  13. const (
  14. apiURL = "https://write.as/api"
  15. devAPIURL = "https://development.write.as/api"
  16. torAPIURL = "http://writeas7pm7rcdqg.onion/api"
  17. )
  18. // Client is used to interact with the Write.as API. It can be used to make
  19. // authenticated or unauthenticated calls.
  20. type Client struct {
  21. baseURL string
  22. // Access token for the user making requests.
  23. token string
  24. // Client making requests to the API
  25. client *http.Client
  26. // UserAgent overrides the default User-Agent header
  27. UserAgent string
  28. }
  29. // defaultHTTPTimeout is the default http.Client timeout.
  30. const defaultHTTPTimeout = 10 * time.Second
  31. // NewClient creates a new API client. By default, all requests are made
  32. // unauthenticated. To optionally make authenticated requests, call `SetToken`.
  33. //
  34. // c := writeas.NewClient()
  35. // c.SetToken("00000000-0000-0000-0000-000000000000")
  36. func NewClient() *Client {
  37. return &Client{
  38. client: &http.Client{Timeout: defaultHTTPTimeout},
  39. baseURL: apiURL,
  40. }
  41. }
  42. // NewTorClient creates a new API client for communicating with the Write.as
  43. // Tor hidden service, using the given port to connect to the local SOCKS
  44. // proxy.
  45. func NewTorClient(port int) *Client {
  46. dialSocksProxy := socks.DialSocksProxy(socks.SOCKS5, fmt.Sprintf("127.0.0.1:%d", port))
  47. transport := &http.Transport{Dial: dialSocksProxy}
  48. return &Client{
  49. client: &http.Client{Transport: transport},
  50. baseURL: torAPIURL,
  51. }
  52. }
  53. // NewDevClient creates a new API client for development and testing. It'll
  54. // communicate with our development servers, and SHOULD NOT be used in
  55. // production.
  56. func NewDevClient() *Client {
  57. return &Client{
  58. client: &http.Client{Timeout: defaultHTTPTimeout},
  59. baseURL: devAPIURL,
  60. }
  61. }
  62. // SetToken sets the user token for all future Client requests. Setting this to
  63. // an empty string will change back to unauthenticated requests.
  64. func (c *Client) SetToken(token string) {
  65. c.token = token
  66. }
  67. // Token returns the user token currently set to the Client.
  68. func (c *Client) Token() string {
  69. return c.token
  70. }
  71. func (c *Client) get(path string, r interface{}) (*impart.Envelope, error) {
  72. method := "GET"
  73. if method != "GET" && method != "HEAD" {
  74. return nil, fmt.Errorf("Method %s not currently supported by library (only HEAD and GET).\n", method)
  75. }
  76. return c.request(method, path, nil, r)
  77. }
  78. func (c *Client) post(path string, data, r interface{}) (*impart.Envelope, error) {
  79. b := new(bytes.Buffer)
  80. json.NewEncoder(b).Encode(data)
  81. return c.request("POST", path, b, r)
  82. }
  83. func (c *Client) put(path string, data, r interface{}) (*impart.Envelope, error) {
  84. b := new(bytes.Buffer)
  85. json.NewEncoder(b).Encode(data)
  86. return c.request("PUT", path, b, r)
  87. }
  88. func (c *Client) delete(path string, data map[string]string) (*impart.Envelope, error) {
  89. r, err := c.buildRequest("DELETE", path, nil)
  90. if err != nil {
  91. return nil, err
  92. }
  93. q := r.URL.Query()
  94. for k, v := range data {
  95. q.Add(k, v)
  96. }
  97. r.URL.RawQuery = q.Encode()
  98. return c.doRequest(r, nil)
  99. }
  100. func (c *Client) request(method, path string, data io.Reader, result interface{}) (*impart.Envelope, error) {
  101. r, err := c.buildRequest(method, path, data)
  102. if err != nil {
  103. return nil, err
  104. }
  105. return c.doRequest(r, result)
  106. }
  107. func (c *Client) buildRequest(method, path string, data io.Reader) (*http.Request, error) {
  108. url := fmt.Sprintf("%s%s", c.baseURL, path)
  109. r, err := http.NewRequest(method, url, data)
  110. if err != nil {
  111. return nil, fmt.Errorf("Create request: %v", err)
  112. }
  113. c.prepareRequest(r)
  114. return r, nil
  115. }
  116. func (c *Client) doRequest(r *http.Request, result interface{}) (*impart.Envelope, error) {
  117. resp, err := c.client.Do(r)
  118. if err != nil {
  119. return nil, fmt.Errorf("Request: %v", err)
  120. }
  121. defer resp.Body.Close()
  122. env := &impart.Envelope{
  123. Code: resp.StatusCode,
  124. }
  125. if result != nil {
  126. env.Data = result
  127. err = json.NewDecoder(resp.Body).Decode(&env)
  128. if err != nil {
  129. return nil, err
  130. }
  131. }
  132. return env, nil
  133. }
  134. func (c *Client) prepareRequest(r *http.Request) {
  135. ua := c.UserAgent
  136. if ua == "" {
  137. ua = "go-writeas v1"
  138. }
  139. r.Header.Add("User-Agent", ua)
  140. r.Header.Add("Content-Type", "application/json")
  141. if c.token != "" {
  142. r.Header.Add("Authorization", "Token "+c.token)
  143. }
  144. }