Go client for the Write.as API https://developers.write.as
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

92 строки
1.9 KiB

  1. package writeas
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/writeas/impart"
  8. "io"
  9. "net/http"
  10. "time"
  11. )
  12. const (
  13. apiURL = "https://write.as/api"
  14. )
  15. type Client struct {
  16. baseURL string
  17. // Access token for the user making requests.
  18. token string
  19. // Client making requests to the API
  20. client *http.Client
  21. }
  22. // defaultHTTPTimeout is the default http.Client timeout.
  23. const defaultHTTPTimeout = 10 * time.Second
  24. func NewClient() *Client {
  25. return &Client{
  26. client: &http.Client{Timeout: defaultHTTPTimeout},
  27. baseURL: apiURL,
  28. }
  29. }
  30. func (c *Client) SetToken(token string) {
  31. c.token = token
  32. }
  33. func (c *Client) get(path string, r interface{}) (*impart.Envelope, error) {
  34. method := "GET"
  35. if method != "GET" && method != "HEAD" {
  36. return nil, errors.New(fmt.Sprintf("Method %s not currently supported by library (only HEAD and GET).\n", method))
  37. }
  38. return c.request(method, path, nil, r)
  39. }
  40. func (c *Client) post(path string, data, r interface{}) (*impart.Envelope, error) {
  41. b := new(bytes.Buffer)
  42. json.NewEncoder(b).Encode(data)
  43. return c.request("POST", path, b, r)
  44. }
  45. func (c *Client) request(method, path string, data io.Reader, result interface{}) (*impart.Envelope, error) {
  46. url := fmt.Sprintf("%s%s", c.baseURL, path)
  47. r, err := http.NewRequest(method, url, data)
  48. if err != nil {
  49. return nil, fmt.Errorf("Create request: %v", err)
  50. }
  51. c.prepareRequest(r)
  52. resp, err := c.client.Do(r)
  53. if err != nil {
  54. return nil, fmt.Errorf("Request: %v", err)
  55. }
  56. defer resp.Body.Close()
  57. env := &impart.Envelope{
  58. Code: resp.StatusCode,
  59. }
  60. if result != nil {
  61. env.Data = result
  62. }
  63. err = json.NewDecoder(resp.Body).Decode(&env)
  64. if err != nil {
  65. return nil, err
  66. }
  67. return env, nil
  68. }
  69. func (c *Client) prepareRequest(r *http.Request) {
  70. r.Header.Add("User-Agent", "go-writeas v1")
  71. r.Header.Add("Content-Type", "application/json")
  72. if c.token != "" {
  73. r.Header.Add("Authorization", "Token "+c.token)
  74. }
  75. }