users.go49 lines, 1.2 KB
| 1 | package notification |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | |
| 9 | "github.com/google/uuid" |
| 10 | ) |
| 11 | |
| 12 | // Users knows where to reach a user. Events carry user IDs, never addresses: |
| 13 | // an address can change, and events stay in the stream for a month. |
| 14 | type Users interface { |
| 15 | Email(ctx context.Context, id uuid.UUID) (string, error) |
| 16 | } |
| 17 | |
| 18 | // AuthUsers asks the auth service, which owns users. |
| 19 | type AuthUsers struct { |
| 20 | BaseURL string // like http://localhost:8082 |
| 21 | Client *http.Client |
| 22 | } |
| 23 | |
| 24 | func (a AuthUsers) Email(ctx context.Context, id uuid.UUID) (string, error) { |
| 25 | url := a.BaseURL + "/internal/users/" + id.String() |
| 26 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 27 | if err != nil { |
| 28 | return "", err |
| 29 | } |
| 30 | resp, err := a.Client.Do(req) |
| 31 | if err != nil { |
| 32 | return "", fmt.Errorf("auth: %w", err) |
| 33 | } |
| 34 | defer resp.Body.Close() |
| 35 | switch resp.StatusCode { |
| 36 | case http.StatusOK: |
| 37 | case http.StatusNotFound: |
| 38 | return "", Permanent(fmt.Errorf("user %s not found", id)) |
| 39 | default: |
| 40 | return "", fmt.Errorf("auth: %s", resp.Status) |
| 41 | } |
| 42 | var user struct { |
| 43 | Email string `json:"email"` |
| 44 | } |
| 45 | if err := json.NewDecoder(resp.Body).Decode(&user); err != nil { |
| 46 | return "", fmt.Errorf("auth: decode user: %w", err) |
| 47 | } |
| 48 | return user.Email, nil |
| 49 | } |