-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
87 lines (70 loc) · 1.4 KB
/
client.go
File metadata and controls
87 lines (70 loc) · 1.4 KB
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
package serials_now_api
import (
"net/http"
"net/http/cookiejar"
"net/url"
)
const (
LoginCookieName = "Login"
PasswordCookieName = "Password"
)
type Client struct {
baseUri *url.URL
client *http.Client
}
func NewClient(baseUri string) (*Client, error) {
uri, err := url.Parse(baseUri)
if err != nil {
return &Client{}, err
}
jar, err := cookiejar.New(nil)
if err != nil {
return &Client{}, err
}
return &Client{
baseUri: uri,
client: &http.Client{
Jar: jar,
},
}, nil
}
func (c *Client) Send(endpoint EndpointInterface) error {
req, err := endpoint.BuildHttpRequest()
if err != nil {
return err
}
req.Host = c.baseUri.Host
req.URL.Scheme = c.baseUri.Scheme
req.URL.Host = c.baseUri.Host
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return endpoint.ParseResponse(resp)
}
func (c *Client) SetLogin(login string) {
c.SetCookie(LoginCookieName, login)
}
func (c *Client) SetPassword(password string) {
c.SetCookie(PasswordCookieName, password)
}
func (c *Client) SetCookie(name, value string) {
set := false
cookies := c.client.Jar.Cookies(c.baseUri)
for _, cookie := range cookies {
if cookie.Name == name {
cookie.Value = value
set = true
break
}
}
if !set {
cookie := &http.Cookie{
Name: name,
Value: value,
}
cookies = append(cookies, cookie)
}
c.client.Jar.SetCookies(c.baseUri, cookies)
}