Go client for the Write.as API https://developers.write.as
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.

70 regels
1.6 KiB

  1. package writeas
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. )
  8. type (
  9. // AuthUser represents a just-authenticated user. It contains information
  10. // that'll only be returned once (now) per user session.
  11. AuthUser struct {
  12. AccessToken string `json:"access_token,omitempty"`
  13. Password string `json:"password,omitempty"`
  14. User *User `json:"user"`
  15. }
  16. // User represents a registered Write.as user.
  17. User struct {
  18. Username string `json:"username"`
  19. Email string `json:"email"`
  20. Created time.Time `json:"created"`
  21. // Optional properties
  22. Subscription *UserSubscription `json:"subscription"`
  23. }
  24. // UserSubscription contains information about a user's Write.as
  25. // subscription.
  26. UserSubscription struct {
  27. Name string `json:"name"`
  28. Begin time.Time `json:"begin"`
  29. End time.Time `json:"end"`
  30. AutoRenew bool `json:"auto_renew"`
  31. Active bool `json:"is_active"`
  32. Delinquent bool `json:"is_delinquent"`
  33. }
  34. )
  35. // GetMe retrieves the authenticated User's information.
  36. // See: https://developers.write.as/docs/api/#retrieve-authenticated-user
  37. func (c *Client) GetMe(ctx context.Context, verbose bool) (*User, error) {
  38. if c.Token() == "" {
  39. return nil, fmt.Errorf("Unable to get user; no access token given.")
  40. }
  41. params := ""
  42. if verbose {
  43. params = "?verbose=true"
  44. }
  45. env, err := c.get(ctx, "/me"+params, nil)
  46. if err != nil {
  47. return nil, err
  48. }
  49. status := env.Code
  50. if status == http.StatusUnauthorized {
  51. return nil, fmt.Errorf("invalid or expired token")
  52. }
  53. var u *User
  54. var ok bool
  55. if u, ok = env.Data.(*User); !ok {
  56. return nil, fmt.Errorf("Wrong data returned from API.")
  57. }
  58. return u, nil
  59. }