14 var defaultClient Client = Client{Client: http.DefaultClient}
16 func Lookup(id string) (*Activity, error) {
17 return defaultClient.Lookup(id)
20 func LookupActor(id string) (*Actor, error) {
21 return defaultClient.LookupActor(id)
30 func (c *Client) Lookup(id string) (*Activity, error) {
31 if !strings.HasPrefix(id, "http") {
32 return nil, fmt.Errorf("id is not a HTTP URL")
35 c.Client = http.DefaultClient
38 req, err := http.NewRequest(http.MethodGet, id, nil)
42 req.Header.Set("Accept", ContentType)
43 if c.Key != nil && c.Actor != nil {
44 if err := Sign(req, c.Key, c.Actor.PublicKey.ID); err != nil {
45 return nil, fmt.Errorf("sign http request: %w", err)
48 resp, err := c.Do(req)
52 defer resp.Body.Close()
53 if resp.StatusCode == http.StatusNotFound {
54 return nil, ErrNotExist
55 } else if resp.StatusCode >= 400 {
56 return nil, fmt.Errorf("non-ok response status %s", resp.Status)
58 return Decode(resp.Body)
61 func (c *Client) LookupActor(id string) (*Actor, error) {
62 activity, err := c.Lookup(id)
66 return activityToActor(activity), nil
69 func activityToActor(activity *Activity) *Actor {
71 AtContext: activity.AtContext,
75 Username: activity.Username,
76 Inbox: activity.Inbox,
77 Outbox: activity.Outbox,
78 Followers: activity.Followers,
79 Published: activity.Published,
80 Summary: activity.Summary,
82 if activity.PublicKey != nil {
83 actor.PublicKey = *activity.PublicKey
88 func (c *Client) Send(inbox string, activity *Activity) (*Activity, error) {
89 b, err := json.Marshal(activity)
91 return nil, fmt.Errorf("encode outgoing activity: %w", err)
93 req, err := http.NewRequest(http.MethodPost, inbox, bytes.NewReader(b))
97 req.Header.Set("Content-Type", ContentType)
98 if err := Sign(req, c.Key, c.Actor.PublicKey.ID); err != nil {
99 return nil, fmt.Errorf("sign outgoing request: %w", err)
101 resp, err := c.Do(req)
105 switch resp.StatusCode {
106 case http.StatusOK, http.StatusAccepted, http.StatusNoContent:
108 case http.StatusNotFound:
109 return nil, fmt.Errorf("no such inbox %s", inbox)
111 io.Copy(os.Stderr, resp.Body)
113 return nil, fmt.Errorf("non-ok response status %s", resp.Status)