-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
103 lines (85 loc) · 2.08 KB
/
client.go
File metadata and controls
103 lines (85 loc) · 2.08 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Simple library to test webhook calls, ideal for testing callbacks in a CI
// server that doesn't accept calls from the outside world.
//
// Features:
//
// - Create tokens, inspect results
//
// - Can be configured to use a self-hosted webhook.site instance
//
// - Zero dependencies!
package webhooksite
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
)
// The default endpoint, but obviously you can use any self-hosted instance as
// well.
const Endpoint = "https://webhook.site"
type Client struct {
endpoint string
Client *http.Client
}
func New() *Client {
return NewWithEndpoint(Endpoint)
}
func NewWithEndpoint(endpoint string) *Client {
return &Client{
endpoint: endpoint,
Client: &http.Client{},
}
}
func (c *Client) url(p string) string {
return fmt.Sprintf("%s/%s", strings.TrimSuffix(c.endpoint, "/"), p)
}
func (c *Client) CreateToken() (*Token, error) {
return c.CreateTokenWithOptions(TokenOptions{})
}
func (c *Client) CreateTokenWithOptions(opts TokenOptions) (*Token, error) {
in, err := json.Marshal(opts)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.url("token"), bytes.NewReader(in))
if err != nil {
return nil, err
}
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return nil, fmt.Errorf("CreateTokenWithOptions: Unexpected status code: %d", resp.StatusCode)
}
r := &Token{}
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return nil, err
}
r.URL = c.url(r.UUID)
return r, nil
}
func (c *Client) GetRequests(id string) (*Requests, error) {
req, err := http.NewRequest("GET", c.url(fmt.Sprintf("/token/%s/requests", id)), nil)
if err != nil {
return nil, err
}
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GetRequests: Unexpected status code: %d", resp.StatusCode)
}
r := &Requests{}
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return nil, err
}
return r, nil
}