-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
78 lines (64 loc) · 1.63 KB
/
client.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
type Client struct {
BaseURL string
apiKey string
HTTPClient *http.Client
}
type errorResponse struct {
Err string `json:"err"`
}
type RundeckResponse struct {
JobId string `json:"jobId"`
ExecutionId string `json:"executionId"`
}
func NewClient(BaseURLV1, apiKey string) *Client {
return &Client{
BaseURL: BaseURLV1,
apiKey: apiKey,
HTTPClient: &http.Client{
Timeout: 2 * time.Second,
},
}
}
func (c *Client) sendRequest(req *http.Request, logger *log.Logger) error {
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")
req.Header.Set("Authorization", c.apiKey)
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
var errRes errorResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
return errors.New(errRes.Err)
}
return fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
body, _ := ioutil.ReadAll(res.Body)
var response RundeckResponse
if err = json.Unmarshal(body, &response); err != nil {
return err
}
logger.Println("JobID -> ", response.JobId, " executionId -> ", response.ExecutionId)
return nil
}
func (c *Config) postRequest(data []byte, logger *log.Logger) *http.Request {
reqBody := bytes.NewBuffer(data)
req, err := http.NewRequest(http.MethodPost, c.Target.URL, reqBody)
if err != nil {
logger.Printf("Unable to make request: %v", err)
}
return req
}