-
Notifications
You must be signed in to change notification settings - Fork 0
/
private.go
53 lines (44 loc) · 998 Bytes
/
private.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
package glinet
import (
"context"
"fmt"
"github.com/imroc/req/v3"
"net/http"
)
func unmarshalResp(resp *req.Response, obj any) error {
if resp.GetStatusCode() != http.StatusOK {
return fmt.Errorf("bad status code: %w", ErrUnexpected)
}
var status struct {
Code Code `json:"code"`
}
if err := resp.UnmarshalJson(&status); err != nil {
return err
}
if status.Code == CodeBadToken {
return ErrUnauthorized
}
if obj != nil {
if err := resp.UnmarshalJson(&obj); err != nil {
return err
}
}
return nil
}
func fetchToken(ctx context.Context, addr string, password string) (string, error) {
client := req.C().EnableInsecureSkipVerify()
resp, err := client.R().
SetContext(ctx).
SetFormData(map[string]string{"pwd": password}).
Post(fmt.Sprintf("https://%s/api/router/login", addr))
if err != nil {
return "", err
}
var m struct {
Token string `json:"token"`
}
if err := resp.UnmarshalJson(&m); err != nil {
return "", err
}
return m.Token, nil
}