/
webhook.go
55 lines (50 loc) · 1.33 KB
/
webhook.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
package cmd
import (
"bytes"
"crypto/tls"
"fmt"
"net/http"
"os"
"time"
"github.com/spf13/cobra"
"sigs.k8s.io/controller-runtime/pkg/manager/signals"
)
func NewWebhookCommand() *cobra.Command {
var (
url string
data string
httpClient = http.Client{
Timeout: 5 * time.Second,
Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
)
command := &cobra.Command{
Use: "webhook",
Short: "Generate webhook event source messages",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
validateGlobalParameters(cmd, args)
if url == "" {
fmt.Printf("\nUrl is required\n\n")
cmd.HelpFunc()(cmd, args)
os.Exit(1)
}
stressRun(signals.SetupSignalHandler(), func() error {
resp, err := httpClient.Post(url, "application/json", bytes.NewBuffer([]byte(data)))
if err != nil {
return fmt.Errorf("failed to post an event: %w", err)
}
if resp.StatusCode == 200 {
return nil
}
return fmt.Errorf("failed to post an message, response code: %d", resp.StatusCode)
})
},
}
command.Flags().StringVar(&url, "url", "", "The url to post messages")
command.Flags().StringVar(&data, "data", "{}", "The data to post")
return command
}