forked from cooldogedev/spectrum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dial.go
53 lines (43 loc) · 1.32 KB
/
dial.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
package api
import (
"errors"
"fmt"
"net"
"github.com/cooldogedev/spectrum/api/packet"
)
// Dial establishes a TCP connection to the specified API service address using the provided token.
// It returns a new Client instance if the connection and authentication are successful.
// Otherwise, it returns an error indicating the failure reason.
func Dial(addr, token string) (c *Client, err error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
}
c = NewClient(conn, packet.NewPool())
defer func() {
if err != nil {
_ = c.Close()
}
}()
if err := c.WritePacket(&packet.ConnectionRequest{Token: token}); err != nil {
return nil, err
}
connectionResponsePacket, err := c.ReadPacket()
if err != nil {
return nil, err
}
connectionResponse, ok := connectionResponsePacket.(*packet.ConnectionResponse)
if !ok {
return nil, fmt.Errorf("expected connection response, got %d", connectionResponse.ID())
}
if connectionResponse.Response == packet.ResponseFail {
return nil, errors.New("connection failed")
}
if connectionResponse.Response == packet.ResponseUnauthorized {
return nil, errors.New("connection unauthorized")
}
if connectionResponse.Response != packet.ResponseSuccess {
return nil, fmt.Errorf("received an unknown response code %d", connectionResponse.ID())
}
return c, nil
}