-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
101 lines (82 loc) · 1.99 KB
/
client.go
File metadata and controls
101 lines (82 loc) · 1.99 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
package snowgo
import (
"context"
"io"
"net/http"
"strings"
)
const (
// DefaultSuffix is the default ServiceNow REST API URL suffix
DefaultSuffix = ".service-now.com/api"
)
// Request is an interface for ServiceNow REST API requests
type Request interface {
Marshal() (*http.Request, error)
}
// Response is an interface for ServiceNow REST API responses
type Response interface {
Unmarshal(*http.Response) error
}
// RequestEditorFn is a function that can be used to modify an HTTP request
type RequestEditorFn func(ctx context.Context, req *http.Request) error
// Client is an opaque type that holds the client configuration
type Client struct {
http *http.Client
server string
requestEditorFn []RequestEditorFn
}
// Opt is a functional option type for configuring the client
type Opt func(*Client)
// WithHTTPClient sets the HTTP client to use
func WithHTTPClient(http *http.Client) Opt {
return func(c *Client) {
c.http = http
}
}
// WithRequestEditorFn sets the request editor function to use
func WithRequestEditorFn(fn ...RequestEditorFn) Opt {
return func(c *Client) {
c.requestEditorFn = append(c.requestEditorFn, fn...)
}
}
// New returns a new ServiceNow client
func New(server string, opts ...Opt) *Client {
c := &Client{
http: http.DefaultClient,
server: server,
}
if !strings.HasSuffix(c.server, "/") {
c.server += "/"
}
for _, opt := range opts {
opt(c)
}
return c
}
// Do sends an HTTP request and returns an HTTP response
func (c *Client) Do(ctx context.Context, req Request, resp Response) error {
httpReq, err := req.Marshal()
if err != nil {
return err
}
for _, fn := range c.requestEditorFn {
err := fn(ctx, httpReq)
if err != nil {
return err
}
}
httpResp, err := c.http.Do(httpReq.WithContext(ctx))
if err != nil {
return err
}
err = resp.Unmarshal(httpResp)
if err != nil {
return err
}
_, err = io.Copy(io.Discard, httpResp.Body)
if err != nil {
return err
}
defer httpResp.Body.Close()
return nil
}