master
go 75 lines 1.18 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package spigotmc
4
5 import (
6 "time"
7
8 "github.com/gorcon/rcon"
9 )
10
11 type rconConn interface {
12 connect() error
13 disconnect() error
14 queryTps() (string, error)
15 queryList() (string, error)
16 }
17
18 const (
19 cmdTPS = "tps"
20 cmdList = "list"
21 )
22
23 func newRconConn(cfg Config) rconConn {
24 return &rconClient{
25 addr: cfg.Address,
26 password: cfg.Password,
27 timeout: cfg.Timeout.Duration(),
28 }
29 }
30
31 type rconClient struct {
32 conn *rcon.Conn
33 addr string
34 password string
35 timeout time.Duration
36 }
37
38 func (c *rconClient) queryTps() (string, error) {
39 return c.query(cmdTPS)
40 }
41
42 func (c *rconClient) queryList() (string, error) {
43 return c.query(cmdList)
44 }
45
46 func (c *rconClient) query(cmd string) (string, error) {
47 resp, err := c.conn.Execute(cmd)
48 if err != nil {
49 return "", err
50 }
51 return resp, nil
52 }
53
54 func (c *rconClient) connect() error {
55 _ = c.disconnect()
56
57 conn, err := rcon.Dial(c.addr, c.password, rcon.SetDialTimeout(c.timeout), rcon.SetDeadline(c.timeout))
58 if err != nil {
59 return err
60 }
61
62 c.conn = conn
63
64 return nil
65 }
66
67 func (c *rconClient) disconnect() error {
68 if c.conn != nil {
69 err := c.conn.Close()
70 c.conn = nil
71 return err
72 }
73
74 return nil
75 }