-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudflare.go
64 lines (52 loc) · 1.35 KB
/
cloudflare.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
type CloudflareResponse struct {
IceServers CloudflareIceServers `json:"iceServers"`
}
type CloudflareIceServers struct {
Urls []string `json:"urls"`
Username string `json:"username"`
Password string `json:"credential"`
}
func requestCredentials(keyId string, params Params, payload Payload) (*CloudflareResponse, error) {
upstream := fmt.Sprintf("https://rtc.live.cloudflare.com/v1/turn/keys/%s/credentials/generate", keyId)
jsonPayload, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", upstream, bytes.NewBuffer(jsonPayload))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+params["key"])
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
// Send the request via a client
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Read the response body
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != 201 {
return nil, errors.New("invalid response: " + string(body))
}
var credentials CloudflareResponse
err = json.Unmarshal(body, &credentials)
if err != nil {
return nil, err
}
return &credentials, nil
}