blob: 80d919f00121582c38037efdf3170de1fcc79e02 (
plain) (
blame)
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
|
package steam
import (
"encoding/json"
"fmt"
"math/rand"
"net/http"
"sync"
"time"
"github.com/Philipp15b/go-steam/netutil"
)
// Load initial server list from Steam Directory Web API.
// Call InitializeSteamDirectory() before Connect() to use
// steam directory server list instead of static one.
func InitializeSteamDirectory() error {
return steamDirectoryCache.Initialize()
}
var steamDirectoryCache *steamDirectory = &steamDirectory{}
type steamDirectory struct {
sync.RWMutex
servers []string
isInitialized bool
}
// Get server list from steam directory and save it for later
func (sd *steamDirectory) Initialize() error {
sd.Lock()
defer sd.Unlock()
client := new(http.Client)
resp, err := client.Get(fmt.Sprintf("https://api.steampowered.com/ISteamDirectory/GetCMList/v1/?cellId=0"))
if err != nil {
return err
}
defer resp.Body.Close()
r := struct {
Response struct {
ServerList []string
Result uint32
Message string
}
}{}
if err = json.NewDecoder(resp.Body).Decode(&r); err != nil {
return err
}
if r.Response.Result != 1 {
return fmt.Errorf("Failed to get steam directory, result: %v, message: %v\n", r.Response.Result, r.Response.Message)
}
if len(r.Response.ServerList) == 0 {
return fmt.Errorf("Steam returned zero servers for steam directory request\n")
}
sd.servers = r.Response.ServerList
sd.isInitialized = true
return nil
}
func (sd *steamDirectory) GetRandomCM() *netutil.PortAddr {
sd.RLock()
defer sd.RUnlock()
if !sd.isInitialized {
panic("steam directory is not initialized")
}
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
addr := netutil.ParsePortAddr(sd.servers[rng.Int31n(int32(len(sd.servers)))])
return addr
}
func (sd *steamDirectory) IsInitialized() bool {
sd.RLock()
defer sd.RUnlock()
isInitialized := sd.isInitialized
return isInitialized
}
|