-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
95 lines (79 loc) · 2.05 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package librus_api_go
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
)
var host = "https://api.librus.pl/"
var Headers = []LibrusHeader{
{
Key: "Authorization",
Value: "Basic Mjg6ODRmZGQzYTg3YjAzZDNlYTZmZmU3NzdiNThiMzMyYjE=",
},
{
Key: "Content-Type",
Value: "application/x-www-form-urlencoded",
},
}
// HTTPClient represents http client :)
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
func (l *Librus) CreateSession() error {
postData := url.Values{}
postData.Set("username", l.Username)
postData.Set("password", l.Password)
postData.Set("librus_long_term_token", "1")
postData.Set("grant_type", "password")
// request
req, err := http.NewRequest("POST", host+"OAuth/Token", strings.NewReader(postData.Encode()))
// add headers
for _, h := range Headers {
req.Header.Set(h.Key, h.Value)
}
if err != nil {
return err
}
// response
res, err := l.Client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
// check response code
if res.StatusCode != http.StatusOK {
return fmt.Errorf("Error status code, wanted: %v, got: %v", http.StatusOK, res.StatusCode)
}
// decode json response
okResponse := new(OKResponse)
err = json.NewDecoder(res.Body).Decode(okResponse)
if err != nil {
return err
}
// change authorization header
Headers[0].Value = "Bearer " + okResponse.AccessToken
return nil
}
// GetData returns data from url e.g. https://api.librus.pl/2.0/LuckyNumbers
func (l *Librus) GetData(url string) (*http.Response, error) {
// request
req, err := http.NewRequest("GET", host+"2.0/"+url, nil)
// add headers
for _, h := range Headers {
if h.Key == "Authorization" && !strings.HasPrefix(h.Value, "Bearer ") {
return nil, errors.New("Wrong authorization header, should be Bearer")
}
req.Header.Set(h.Key, h.Value)
}
if err != nil {
return nil, err
}
res, err := l.Client.Do(req)
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Error status code, wanted: %v, got: %v", http.StatusOK, res.StatusCode)
}
return res, nil
}