forked from Philipp15b/go-steamapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
steamapi.go
73 lines (62 loc) · 1.58 KB
/
steamapi.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
// Package steamapi provides an interface to the
// Steam Web API methods.
package steamapi
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"sync"
)
const steamUrl = "http://api.steampowered.com/%v/%v/v%v/"
// Api represents a Steam Web API handler
type Api struct {
apiKey string
apiKeyMutex *sync.RWMutex
}
// Create new Steam Web API handler
func NewSteamApi(apiKey string) (*Api, error) {
api := &Api{apiKey: apiKey, apiKeyMutex: &sync.RWMutex{}}
return api, nil
}
func (api *Api) GetApiKey() string {
api.apiKeyMutex.RLock()
apiKey := api.apiKey
api.apiKeyMutex.RUnlock()
return apiKey
}
func (api *Api) ChangeApiKey(apiKey string) error {
api.apiKeyMutex.Lock()
api.apiKey = apiKey
api.apiKeyMutex.Unlock()
return nil
}
// A SteamMethod represents a Steam Web API method.
type SteamMethod string
// Creates a new SteamMethod.
func NewSteamMethod(interf, method string, version int) SteamMethod {
m := fmt.Sprintf(steamUrl, interf, method, strconv.Itoa(version))
return SteamMethod(m)
}
// Makes a request to the Steam Web API with the given
// url values and stores the result in v.
//
// Returns an error if the return status code was not 200.
func (s SteamMethod) Request(data url.Values, v interface{}) error {
url := string(s)
if data != nil {
url += "?" + data.Encode()
}
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return errors.New(fmt.Sprintf("Status code %d returned by %v", resp.StatusCode, string(s)))
}
d := json.NewDecoder(resp.Body)
return d.Decode(&v)
}