-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
81 lines (69 loc) · 1.59 KB
/
client.go
File metadata and controls
81 lines (69 loc) · 1.59 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
package main
import (
"bytes"
"context"
"flag_sender/internal/models"
"flag_sender/pkg/plugins"
"fmt"
"io"
"net/http"
"strings"
"github.com/bytedance/sonic"
)
type Client struct {
url string
token string
}
type FlagInfo struct {
Flag string `json:"flag"`
Msg string `json:"msg"`
}
var NewClient plugins.NewClientFunc = func(url, token string) plugins.IClient {
return &Client{
url: url,
token: token,
}
}
func (c *Client) SendFlags(ctx context.Context, flags []string) (map[string]*plugins.FlagResult, error) {
data, err := sonic.Marshal(flags)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "PUT", c.url, bytes.NewBuffer(data))
if err != nil {
return nil, err
}
req.Header.Set("X-Team-Token", c.token)
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("incorrect status code: %d, body: %s", res.StatusCode, body)
}
var flagInfos []*FlagInfo
if err := sonic.Unmarshal(body, &flagInfos); err != nil {
return nil, err
}
flagMap := make(map[string]*plugins.FlagResult)
for _, flagInfo := range flagInfos {
flagStatus := models.FlagStatusReject
if strings.Contains(flagInfo.Msg, "accepted") {
flagStatus = models.FlagStatusSuccess
}
if strings.Contains(flagInfo.Msg, "old") {
flagStatus = models.FlagStatusOld
}
flagMap[flagInfo.Flag] = &plugins.FlagResult{
Status: flagStatus,
Msg: flagInfo.Msg,
}
}
return flagMap, nil
}