-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.go
74 lines (63 loc) · 1.82 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
package gotrix
import (
"context"
"fmt"
"net/url"
"reflect"
"strings"
"github.com/chanbakjsd/gotrix/api"
"github.com/chanbakjsd/gotrix/api/httputil"
"github.com/chanbakjsd/gotrix/event"
"github.com/chanbakjsd/gotrix/state"
)
// Client is an instance of a higher level client.
type Client struct {
*api.Client
SyncOpts SyncOptions
Handler Handler
State State
ctx context.Context
next string
cancelFunc func()
closeDone chan struct{}
}
// New creates a client with the provided host URL and the default HTTP client.
// It assumes https if the scheme is not provided.
func New(homeServerHost string) (*Client, error) {
return NewWithClient(httputil.NewClient(), homeServerHost)
}
// NewWithClient creates a client with the provided host URL and the provided client.
// It assumes https if the scheme is not provided.
func NewWithClient(httpClient httputil.Client, serverName string) (*Client, error) {
if !strings.Contains(serverName, "://") {
// First is protocol while second is port.
serverName = "https://" + serverName
}
parsed, err := url.Parse(serverName)
if err != nil {
return nil, fmt.Errorf("cannot parse %s: %w", serverName, err)
}
apiClient := &api.Client{
Client: httpClient,
Endpoints: api.Endpoints{Version: "r0"},
}
apiClient.HomeServer = parsed.Host
apiClient.HomeServerScheme = parsed.Scheme
if vClient, err := apiClient.WithLatestVersion(); err == nil {
apiClient = vClient
}
return &Client{
Client: apiClient,
SyncOpts: DefaultSyncOptions,
Handler: &defaultHandler{
handlers: make(map[event.Type][]reflect.Value),
},
State: state.NewDefault(),
}, nil
}
// WithContext creates a copy of the client that uses the provided context.
func (c Client) WithContext(ctx context.Context) *Client {
c.Client = c.Client.WithContext(ctx)
c.ctx = ctx
return &c
}