-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmanage_tweet.go
74 lines (67 loc) · 2.05 KB
/
manage_tweet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package gotwtr
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
)
func postTweet(ctx context.Context, c *client, body *PostTweetOption) (*PostTweetResponse, error) {
j, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("postTweet json marshal: %w", err)
}
fmt.Println(string(j))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, postTweetURL, bytes.NewBuffer(j))
if err != nil {
return nil, fmt.Errorf("postTweet new request with ctx: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.bearerToken))
req.Header.Set("Content-Type", "application/json")
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("post tweet response: %w", err)
}
defer resp.Body.Close()
var postTweet PostTweetResponse
if err := json.NewDecoder(resp.Body).Decode(&postTweet); err != nil {
return nil, fmt.Errorf("post tweet decode: %w", err)
}
if resp.StatusCode != http.StatusCreated {
return &postTweet, &HTTPError{
APIName: "post tweet",
Status: resp.Status,
URL: req.URL.String(),
}
}
return &postTweet, nil
}
func deleteTweet(ctx context.Context, c *client, tweetID string) (*DeleteTweetResponse, error) {
if tweetID == "" {
return nil, errors.New("delete tweet: tweet id parameter is required")
}
ep := fmt.Sprintf(deleteTweetURL, tweetID)
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, ep, nil)
if err != nil {
return nil, fmt.Errorf("delete tweet new request with ctx: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.bearerToken))
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("delete tweet response: %w", err)
}
defer resp.Body.Close()
var deleteTweet DeleteTweetResponse
if err := json.NewDecoder(resp.Body).Decode(&deleteTweet); err != nil {
return nil, fmt.Errorf("delete tweet decode: %w", err)
}
if resp.StatusCode != http.StatusOK {
return &deleteTweet, &HTTPError{
APIName: "delete tweet",
Status: resp.Status,
URL: req.URL.String(),
}
}
return &deleteTweet, nil
}