-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdestroy.go
77 lines (63 loc) · 1.67 KB
/
destroy.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
package main
import (
"bytes"
"fmt"
"net/http"
"time"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
)
// Destroyer is the data object for destruction
type Destroyer struct {
Endpoint string
Token string
ResourceID string
Org string
Client HTTPClient
}
// NewDestroyer creates a new destruction object
func NewDestroyer(endpoint, token, id, org string, encryptToken bool) (Destroyer, error) {
client := &http.Client{Timeout: 30 * time.Second}
t := token
if encryptToken {
crytpT, err := bcrypt.GenerateFromPassword([]byte(token), 4)
if err != nil {
return Destroyer{}, fmt.Errorf("failed to bcrypt from password: %s", err)
}
t = string(crytpT)
}
return Destroyer{
Endpoint: endpoint,
Token: t,
ResourceID: id,
Org: org,
Client: client,
}, nil
}
// Destroy destroys the instance by 'DELETE'ing it
func (d Destroyer) Destroy() error {
log.Debugf("Destroying with endpoint: %s, resource: %s, org: %s ", d.Endpoint, d.ResourceID, d.Org)
url := fmt.Sprintf("%s/%s/%s", d.Endpoint, d.Org, d.ResourceID)
log.Debugf("Generated URL for delete request: %s", url)
req, err := http.NewRequest(http.MethodDelete, url, bytes.NewReader([]byte{}))
if err != nil {
return err
}
req.Header.Set("X-Forwarded-User", "reaper")
req.Header.Set("X-Auth-token", d.Token)
req.Header.Set("Content-Type", "application/json")
res, err := d.Client.Do(req)
if err != nil {
return err
}
defer func() {
err := res.Body.Close()
if err != nil {
log.Error(err)
}
}()
if res.StatusCode > 299 {
return fmt.Errorf("Got a non-success http response from http DELETE to %s, %d", url, res.StatusCode)
}
return nil
}