-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathroom.go
90 lines (72 loc) · 1.86 KB
/
room.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
package room
import "errors"
const (
ErrAuthRoomCanNotFoundKey = "authToken can not found in response"
)
type IRoom interface {
Send(request *Request) (Response, error)
}
type Room struct {
Connector *Connector
}
func NewRoom(connector *Connector) *Room {
return &Room{Connector: connector}
}
func (r *Room) Send(request *Request) (Response, error) {
return r.Connector.Do(request)
}
type AuthRoom struct {
*Room
AuthRequest *Request
AuthToken string
}
func NewAuthRoom(connector *Connector, authRequest *Request, authToken string) IRoom {
return &AuthRoom{
Room: &Room{Connector: connector},
AuthRequest: authRequest,
AuthToken: authToken,
}
}
func (r *AuthRoom) Send(request *Request) (Response, error) {
if r.AuthRequest != nil {
response, err := r.Connector.Do(r.AuthRequest)
if err != nil {
return response, err
}
if !response.OK() {
return response, err
}
if token, found := findToken(response.ResponseBody(), r.AuthToken); found {
r.Connector.Header.Add("Authorization", "Bearer "+token)
} else {
return response, errors.New(ErrAuthRoomCanNotFoundKey)
}
}
return r.Room.Send(request)
}
type IAuth interface {
Apply(connector *Connector, response Response)
}
type AccessTokenAuth struct{}
func (a AccessTokenAuth) Apply(connector *Connector, response Response) {
connector.Header.Add("Authorization", "Bearer "+response.ResponseBody()["access_token"].(string))
}
func NewAccessTokenAuth() IAuth {
return AccessTokenAuth{}
}
func findToken(responseMap map[string]any, tokenKey string) (string, bool) {
for k, v := range responseMap {
if k == tokenKey {
if strValue, ok := v.(string); ok {
return strValue, true
}
return "", false
}
if nestedData, ok := v.(map[string]any); ok {
if value, found := findToken(nestedData, tokenKey); found {
return value, true
}
}
}
return "", false
}