-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.go
40 lines (33 loc) · 943 Bytes
/
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
package util
import (
"fmt"
"net"
"github.com/cooldogedev/spectrum/api"
"github.com/cooldogedev/spectrum/api/packet"
)
func NewClient(addr string, token string) (*api.Client, error) {
c, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
}
client := api.NewClient(c, packet.NewPool())
if err := client.WritePacket(&packet.ConnectionRequest{Token: token}); err != nil {
_ = client.Close()
return nil, err
}
connectionResponsePacket, err := client.ReadPacket()
if err != nil {
_ = client.Close()
return nil, err
}
connectionResponse, ok := connectionResponsePacket.(*packet.ConnectionResponse)
if !ok {
_ = client.Close()
return nil, fmt.Errorf("expected connection response, got %d", connectionResponse.ID())
}
if connectionResponse.Response != packet.ResponseSuccess {
_ = client.Close()
return nil, fmt.Errorf("connection failed, code %d", connectionResponse.ID())
}
return client, nil
}