-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
80 lines (64 loc) · 1.64 KB
/
api.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
75
76
77
78
79
80
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/charmbracelet/log"
)
const createEndpoint = `https://api.twitch.tv/helix/eventsub/subscriptions`
var (
client = http.Client{
Timeout: time.Second * 5,
}
)
type Credentials struct {
ClientID string
AccessToken string
}
type CreateParams struct {
SubscriptionType string
SubscriptionVersions string
Condition json.RawMessage
}
type createBody struct {
SubscriptionType string `json:"type"`
SubscriptionVersion string `json:"version"`
Condition json.RawMessage `json:"condition"`
Transport Transport `json:"transport"`
}
func CreateWebsocketSubscription(sessionID string, params CreateParams, creds Credentials) error {
buf := new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(createBody{
SubscriptionType: params.SubscriptionType,
SubscriptionVersion: params.SubscriptionVersions,
Condition: params.Condition,
Transport: Transport{
Method: "websocket",
SessionID: sessionID,
},
})
if err != nil {
return err
}
log.Info(buf.String())
req, err := http.NewRequest("POST", createEndpoint, buf)
if err != nil {
return err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", creds.AccessToken))
req.Header.Set("Client-Id", creds.ClientID)
req.Header.Set("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusAccepted {
body, _ := io.ReadAll(res.Body)
return fmt.Errorf("bad status code: %d %s", res.StatusCode, string(body))
}
return nil
}