users.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package discourse
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. )
  7. // UserResponse - Structure of a discourse user api response// UserResponse - Structure of a discourse user api response
  8. type UserResponse struct {
  9. User User `json:"user"`
  10. Errors []string `json:"errors"`
  11. ErrorType string `json:"error_type"`
  12. }
  13. // User - A discoruse User
  14. type User struct {
  15. ID int `json:"id" schema:"external_id"`
  16. Username string `json:"username"`
  17. CanSendPM bool `json:"can_send_private_messages"`
  18. Moderator bool `json:"moderator"`
  19. Admin bool `json:"admin"`
  20. TrustLevel int `json:"trust_level"`
  21. Groups []Group `json:"groups"`
  22. GroupStr string `schema:"groups"`
  23. }
  24. // GetUser - Get a discourse user
  25. func GetUser(config APIConfig, username string) (User, error) {
  26. url := fmt.Sprintf("%s/users/%s.json", config.Endpoint, username)
  27. req, _ := newGetRequest(config, url)
  28. client := getClient()
  29. response, _ := client.Do(req)
  30. var result *UserResponse
  31. json.NewDecoder(response.Body).Decode(&result)
  32. if result.ErrorType != "" {
  33. return User{}, fmt.Errorf("Failed to get discourse user. Error: %s", strings.Join(result.Errors, "; "))
  34. }
  35. return result.User, nil
  36. }
  37. func GetUserByID(config APIConfig, userID int) (User, error) {
  38. url := fmt.Sprintf("%s/admin/users/%d.json", config.Endpoint, userID)
  39. req, _ := newGetRequest(config, url)
  40. client := getClient()
  41. response, _ := client.Do(req)
  42. var result *UserResponse
  43. json.NewDecoder(response.Body).Decode(&result)
  44. if result.ErrorType != "" {
  45. return User{}, fmt.Errorf("Failed to get discourse user. Error: %s", strings.Join(result.Errors, "; "))
  46. }
  47. return result.User, nil
  48. }