-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
116 lines (92 loc) · 2.32 KB
/
client.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package huwlte
import (
"context"
"net/http"
"golang.org/x/xerrors"
)
type ClientOpt func(*Client)
// WithDoer sets the HTTP client used to make requests.
func WithDoer(doer *http.Client) ClientOpt {
return func(c *Client) {
c.doer = doer
}
}
// WithStorage sets the storage used to store the modem session.
func WithStorage(name string, storage SessionStorage) ClientOpt {
return func(client *Client) {
client.sessionStorage = storage
client.sessionName = name
}
}
// WithAdminAuth sets the credentials used to authenticate, when need.
func WithAdminAuth(username, password string) ClientOpt {
return func(c *Client) {
c.adminLogin = username
c.adminPass = password
}
}
// Clients it's XML API wrapper.
type Client struct {
baseURL string
doer *http.Client
session Session
adminLogin string
adminPass string
sessionName string
sessionStorage SessionStorage
Device *ClientDevice
User *ClientUser
Monitoring *ClientMonitoring
Dialup *ClientDialup
Net *ClientNet
SMS *ClientSMS
}
// New creates a new Client instance.
func New(baseURL string, opts ...ClientOpt) *Client {
c := &Client{
baseURL: baseURL,
doer: http.DefaultClient,
}
for _, opt := range opts {
opt(c)
}
c.Device = &ClientDevice{c}
c.User = &ClientUser{c}
c.Monitoring = &ClientMonitoring{c}
c.Dialup = &ClientDialup{c}
c.Net = &ClientNet{c}
c.SMS = &ClientSMS{c}
return c
}
func (client *Client) SaveSession(ctx context.Context) error {
if client.sessionStorage == nil {
return nil
}
return client.sessionStorage.Save(ctx, client.sessionName, &client.session)
}
func (client *Client) ResetSession(ctx context.Context) error {
client.session = Session{}
if client.sessionStorage != nil {
return client.sessionStorage.Remove(ctx, client.sessionName)
}
return nil
}
func (client *Client) LoadSession(ctx context.Context) error {
if client.sessionStorage == nil {
return nil
}
session, err := client.sessionStorage.Load(ctx, client.sessionName)
if err != nil {
return xerrors.Errorf("load session: %w", err)
}
client.session = *session
return nil
}
// getDoer returns the HTTP client used to make requests.
// If it's not set, it returns the default HTTP client.
func (client *Client) getDoer() *http.Client {
if client.doer != nil {
return client.doer
}
return http.DefaultClient
}