-
Notifications
You must be signed in to change notification settings - Fork 2
/
entity_delete.go
106 lines (92 loc) · 2.34 KB
/
entity_delete.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
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
104
105
106
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type deleteResponse struct {
Results bool `json:"results"`
Exception bool `json:"exception,omitempty"`
Message string `json:"message,omitempty"`
ErrorCode int `json:"error_code,omitempty"`
}
func entityDeleteHandler(config clientConfig) func(rw http.ResponseWriter, req *http.Request) {
return func(rw http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
entityType, ok := vars["entity_type"]
if !ok {
log.Errorf("Missing Entity Type")
rw.WriteHeader(http.StatusBadRequest)
return
}
var entityID int
var err error
entityIDStr, ok := vars["id"]
if ok {
entityID, err = strconv.Atoi(entityIDStr)
log.Debugf("Id: %v Error: %s", entityID, err)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
return
}
} else {
rw.WriteHeader(http.StatusBadRequest)
return
}
log.Debugf("Entity: %s - %d", entityType, entityID)
query := map[string]interface{}{
"type": entityType,
"id": entityID,
}
ctx := req.Context()
sgConn := ctx.Value("sgConn")
if sgConn == nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
sg := sgConn.(Shotgun)
sgReq, err := sg.Request("delete", query)
if err != nil {
log.Error("Request Error: ", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
var deleteResp deleteResponse
respBody, err := ioutil.ReadAll(sgReq.Body)
if err != nil {
log.Error(err)
rw.WriteHeader(http.StatusBadGateway)
return
}
log.Debugf("Json Response: %s", respBody)
err = json.Unmarshal(respBody, &deleteResp)
if err != nil {
log.Error(err)
rw.WriteHeader(http.StatusBadGateway)
return
}
log.Debugf("Response: %v", deleteResp)
if deleteResp.Exception {
if strings.Contains(deleteResp.Message, "Permission") {
rw.WriteHeader(http.StatusForbidden)
} else if strings.Contains(deleteResp.Message, "does not exist") {
rw.WriteHeader(http.StatusNotFound)
} else {
rw.WriteHeader(http.StatusBadRequest)
}
rw.Write(bytes.NewBufferString(deleteResp.Message).Bytes())
return
}
// I'm not sure this can even happen
if !deleteResp.Results {
rw.WriteHeader(http.StatusNotFound)
return
}
rw.WriteHeader(http.StatusOK)
}
}