This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
forked from GetStream/stream-chat-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
153 lines (120 loc) · 3.12 KB
/
client.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package stream_chat
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
"github.com/getstream/easyjson"
"github.com/pascaldekloe/jwt"
)
const (
defaultBaseURL = "https://chat-us-east-1.stream-io-api.com"
defaultTimeout = 6 * time.Second
)
type Client struct {
BaseURL string
HTTP *http.Client
apiKey string
apiSecret []byte
authToken string
}
func (c *Client) setHeaders(r *http.Request) {
r.Header.Set("Content-Type", "application/json")
r.Header.Set("X-Stream-Client", "stream-go-client")
r.Header.Set("Authorization", c.authToken)
r.Header.Set("Stream-Auth-Type", "jwt")
}
func (c *Client) parseResponse(resp *http.Response, result easyjson.Unmarshaler) error {
if resp.Body != nil {
defer resp.Body.Close()
}
if resp.StatusCode >= 399 {
msg, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("chat-client: HTTP %s %s status %s: %s", resp.Request.Method, resp.Request.URL, resp.Status, string(msg))
}
if result != nil {
return easyjson.UnmarshalFromReader(resp.Body, result)
}
return nil
}
func (c *Client) requestURL(path string, values url.Values) (string, error) {
_url, err := url.Parse(c.BaseURL + "/" + path)
if err != nil {
return "", errors.New("url.Parse: " + err.Error())
}
if values == nil {
values = make(url.Values)
}
values.Add("api_key", c.apiKey)
_url.RawQuery = values.Encode()
return _url.String(), nil
}
func (c *Client) makeRequest(method string, path string, params url.Values, data interface{}, result easyjson.Unmarshaler) error {
_url, err := c.requestURL(path, params)
if err != nil {
return err
}
var body []byte
if m, ok := data.(easyjson.Marshaler); ok {
body, err = easyjson.Marshal(m)
} else {
body, err = json.Marshal(data)
}
if err != nil {
return err
}
r, err := http.NewRequest(method, _url, bytes.NewReader(body))
if err != nil {
return err
}
c.setHeaders(r)
resp, err := c.HTTP.Do(r)
if err != nil {
return err
}
return c.parseResponse(resp, result)
}
// CreateToken creates new token for user with optional expire time
func (c *Client) CreateToken(userID string, expire time.Time) ([]byte, error) {
if userID == "" {
return nil, errors.New("user ID is empty")
}
params := map[string]interface{}{
"user_id": userID,
}
return c.createToken(params, expire)
}
func (c *Client) createToken(params map[string]interface{}, expire time.Time) ([]byte, error) {
var claims = jwt.Claims{
Set: params,
}
claims.Expires = jwt.NewNumericTime(expire)
return claims.HMACSign(jwt.HS256, c.apiSecret)
}
// NewClient creates new stream chat api client
func NewClient(apiKey string, apiSecret []byte) (*Client, error) {
switch {
case apiKey == "":
return nil, errors.New("API key is empty")
case len(apiSecret) == 0:
return nil, errors.New("API secret is empty")
}
client := &Client{
apiKey: apiKey,
apiSecret: apiSecret,
BaseURL: defaultBaseURL,
HTTP: &http.Client{
Timeout: defaultTimeout,
},
}
token, err := client.createToken(map[string]interface{}{"server": true}, time.Time{})
if err != nil {
return nil, err
}
client.authToken = string(token)
return client, nil
}