A Go Tumblr API v2 Client. https://github.com/bakerolls/gotumblr
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.1KB

  1. package gotumblr
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. )
  10. // Get makes a GET request to the API with properly formatted parameters.
  11. // requestURL: the url you are making the request to.
  12. // values: the parameters needed for the request.
  13. func (c *Client) Get(requestURL string, values url.Values) (CompleteResponse, error) {
  14. fullURL := c.host + requestURL + "?" + values.Encode()
  15. req, err := http.NewRequest("GET", fullURL, nil)
  16. if err != nil {
  17. return CompleteResponse{}, err
  18. }
  19. for k, v := range c.headers {
  20. req.Header.Set(k, v)
  21. }
  22. if err := c.service.Sign(req, c.userConfig); err != nil {
  23. return CompleteResponse{}, err
  24. }
  25. res, err := c.client.Do(req)
  26. if err != nil {
  27. return CompleteResponse{}, err
  28. }
  29. defer res.Body.Close()
  30. body, err := ioutil.ReadAll(res.Body)
  31. if err != nil {
  32. return CompleteResponse{}, err
  33. }
  34. var data CompleteResponse
  35. if err := json.Unmarshal(body, &data); err != nil {
  36. return CompleteResponse{}, err
  37. }
  38. if data.Meta.Status < 200 || data.Meta.Status >= 300 {
  39. return data, fmt.Errorf(data.Meta.Msg)
  40. }
  41. return data, nil
  42. }
  43. // Post makes a POST request to the API, allows for multipart data uploads.
  44. // requestURL: the url you are making the request to.
  45. // values: all the parameters needed for the request.
  46. func (c *Client) Post(requestURL string, values url.Values) (CompleteResponse, error) {
  47. fullURL := c.host + requestURL
  48. req, err := http.NewRequest("POST", fullURL, strings.NewReader(values.Encode()))
  49. if err != nil {
  50. return CompleteResponse{}, err
  51. }
  52. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  53. for k, v := range c.headers {
  54. req.Header.Set(k, v)
  55. }
  56. c.service.Sign(req, c.userConfig)
  57. res, err := c.client.Do(req)
  58. if err != nil {
  59. return CompleteResponse{}, err
  60. }
  61. defer res.Body.Close()
  62. body, err := ioutil.ReadAll(res.Body)
  63. if err != nil {
  64. return CompleteResponse{}, err
  65. }
  66. var data CompleteResponse
  67. if err := json.Unmarshal(body, &data); err != nil {
  68. return CompleteResponse{}, err
  69. }
  70. if data.Meta.Status < 200 || data.Meta.Status >= 300 {
  71. return data, fmt.Errorf(data.Meta.Msg)
  72. }
  73. return data, nil
  74. }