-
Notifications
You must be signed in to change notification settings - Fork 15
/
announce.go
101 lines (83 loc) 路 2.32 KB
/
announce.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
adminserver "github.com/ipni/index-provider/server/admin/http"
"github.com/urfave/cli/v2"
)
var AnnounceCmd = &cli.Command{
Name: "announce",
Usage: "Publish an announcement message for the latest advertisement",
Flags: announceFlags,
Action: announceCommand,
}
var announceFlags = []cli.Flag{
adminAPIFlag,
}
var AnnounceHttpCmd = &cli.Command{
Name: "announce-http",
Usage: "Publish an announcement message for the latest advertisement to a specific indexer via http",
Flags: announceHttpFlags,
Action: announceHttpCommand,
}
var announceHttpFlags = []cli.Flag{
adminAPIFlag,
indexerFlag,
}
func announceCommand(cctx *cli.Context) error {
req, err := http.NewRequestWithContext(cctx.Context, http.MethodPost, adminAPIFlagValue+"/admin/announce", nil)
if err != nil {
return err
}
cl := &http.Client{}
resp, err := cl.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Handle failed requests
if resp.StatusCode != http.StatusOK {
return errFromHttpResp(resp)
}
var res adminserver.AnnounceRes
if _, err := res.ReadFrom(resp.Body); err != nil {
return fmt.Errorf("received ok response from server but cannot decode response body. %v", err)
}
msg := fmt.Sprintf("Announced latest advertisement: %s\n", res.AdvId)
_, err = cctx.App.Writer.Write([]byte(msg))
return err
}
func announceHttpCommand(cctx *cli.Context) error {
indexer := cctx.String("indexer")
params := map[string][]byte{
"indexer": []byte(indexer),
}
bodyData, err := json.Marshal(¶ms)
if err != nil {
return err
}
body := bytes.NewBuffer(bodyData)
req, err := http.NewRequestWithContext(cctx.Context, http.MethodPost, adminAPIFlagValue+"/admin/announcehttp", body)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
cl := &http.Client{}
resp, err := cl.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errFromHttpResp(resp)
}
var res adminserver.AnnounceRes
if _, err := res.ReadFrom(resp.Body); err != nil {
return fmt.Errorf("received ok response from server but cannot decode response body. %v", err)
}
msg := fmt.Sprintf("Announced latest advertisement via HTTP: %s\n", res.AdvId)
_, err = cctx.App.Writer.Write([]byte(msg))
return err
}