-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
74 lines (59 loc) · 1.75 KB
/
session.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
74
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"github.com/krozlink/betting"
"github.com/valyala/fasthttp"
)
type Credentials struct {
APIKey string `json:"api_key"`
Login string `json:"login"`
Password string `json:"password"`
Certificate string `json:"certificate"`
CertificateKey string `json:"certificate_key"`
}
func NewBetfairSession(c *Credentials) (*betting.Betfair, error) {
bet := betting.NewBet(c.APIKey)
key, err := getSessionKey([]byte(c.Certificate), []byte(c.CertificateKey), c.APIKey, c.Login, c.Password)
if err != nil {
return nil, err
}
bet.SessionKey = key
return bet, nil
}
func getSessionKey(certData []byte, keyData []byte, APIKey, login, password string) (string, error) {
session := &betting.Session{}
cert, err := tls.X509KeyPair(certData, keyData)
if err != nil {
return "", err
}
client := fasthttp.Client{TLSConfig: &tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}}
req, resp := fasthttp.AcquireRequest(), fasthttp.AcquireResponse()
req.SetRequestURI(betting.CertURL)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("X-Application", APIKey)
req.Header.SetMethod("POST")
bufferString := bytes.NewBuffer([]byte{})
bufferString.WriteString(`username=`)
bufferString.WriteString(login)
bufferString.WriteString(`&password=`)
bufferString.WriteString(password)
req.SetBody(bufferString.Bytes())
err = client.Do(req, resp)
if err != nil {
return "", err
}
err = json.Unmarshal(resp.Body(), session)
if err != nil {
return "", err
}
switch session.LoginStatus {
case betting.LS_SUCCESS:
return session.SessionToken, nil
default:
err = errors.New(string(session.LoginStatus))
}
return "", err
}