-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.go
68 lines (56 loc) · 1.43 KB
/
token.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
package smmssdk
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
)
type TokenRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
func (r *TokenRequest) Request(ctx context.Context) (*http.Request, error) {
if r == nil {
return nil, fmt.Errorf("invalid request is nil")
}
method := http.MethodPost
url := fmt.Sprintf("%s/token", baseURL)
buf, err := json.Marshal(r)
if err != nil {
return nil, err
}
body := bytes.NewBuffer(buf)
slog.InfoContext(ctx, "sending request", slog.String("body", body.String()))
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, err
}
//req.Header.Set("Content-Type", "application/x-www-form-urlencoded") // todo
req.Header.Set("Content-Type", "application/json") // todo:
return req, nil
}
func NewTokenRequest() *TokenRequest {
return &TokenRequest{}
}
type TokenResponse struct {
Success bool `json:"success"`
Code string `json:"code"`
Message string `json:"message"`
Data struct {
Token string `json:"token"`
} `json:"data"`
RequestId string `json:"requestId"`
}
func (c *Client) Token(ctx context.Context, req *TokenRequest) (*TokenResponse, error) {
return c.token(ctx, req)
}
func (c *Client) token(ctx context.Context, req *TokenRequest) (*TokenResponse, error) {
var rsp TokenResponse
err := c.do(ctx, req, &rsp)
if err != nil {
return nil, err
}
return &rsp, nil
}