forked from canonical/lxd
/
response.go
237 lines (195 loc) · 5.26 KB
/
response.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package main
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"github.com/lxc/lxd"
"github.com/lxc/lxd/shared"
"github.com/mattn/go-sqlite3"
)
type resp struct {
Type lxd.ResponseType `json:"type"`
Status string `json:"status"`
StatusCode shared.OperationStatus `json:"status_code"`
Metadata interface{} `json:"metadata"`
}
type Response interface {
Render(w http.ResponseWriter) error
}
type syncResponse struct {
success bool
metadata interface{}
}
/*
fname: name of the file without path
headers: any other headers that should be set in the response
*/
type fileResponse struct {
req *http.Request
path string
filename string
headers map[string]string
}
func FileResponse(r *http.Request, path string, filename string, headers map[string]string) Response {
return &fileResponse{r, path, filename, headers}
}
func (r *fileResponse) Render(w http.ResponseWriter) error {
f, err := os.Open(r.path)
if err != nil {
return err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return err
}
if r.headers != nil {
for k, v := range r.headers {
w.Header().Set(k, v)
}
}
http.ServeContent(w, r.req, r.filename, fi.ModTime(), f)
return nil
}
func WriteJson(w http.ResponseWriter, body interface{}) error {
var output io.Writer
var captured *bytes.Buffer
output = w
if *debug {
captured = &bytes.Buffer{}
output = io.MultiWriter(w, captured)
}
err := json.NewEncoder(output).Encode(body)
if captured != nil {
shared.DebugJson(captured)
}
return err
}
func (r *syncResponse) Render(w http.ResponseWriter) error {
status := shared.Success
if !r.success {
status = shared.Failure
}
resp := resp{Type: lxd.Sync, Status: status.String(), StatusCode: status, Metadata: r.metadata}
return WriteJson(w, resp)
}
/*
* This function and AsyncResponse are simply wrappers for the response so
* users don't have to remember whether to use {}s or ()s when building
* responses.
*/
func SyncResponse(success bool, metadata interface{}) Response {
return &syncResponse{success, metadata}
}
var EmptySyncResponse = &syncResponse{true, make(map[string]interface{})}
type async struct {
Type lxd.ResponseType `json:"type"`
Status string `json:"status"`
StatusCode shared.OperationStatus `json:"status_code"`
Operation string `json:"operation"`
Resources map[string][]string `json:"resources"`
Metadata interface{} `json:"metadata"`
}
type asyncResponse struct {
run func() shared.OperationResult
cancel func() error
ws shared.OperationWebsocket
resources map[string][]string
metadata shared.Jmap
done chan shared.OperationResult
}
func (r *asyncResponse) Render(w http.ResponseWriter) error {
op, err := CreateOperation(r.metadata, r.resources, r.run, r.cancel, r.ws)
if err != nil {
return err
}
err = StartOperation(op)
if err != nil {
return err
}
body := async{Type: lxd.Async, Status: shared.OK.String(), StatusCode: shared.OK, Operation: op}
if r.ws != nil {
body.Metadata = r.ws.Metadata()
} else if r.metadata != nil {
body.Metadata = r.metadata
}
if r.resources != nil {
resources := make(map[string][]string)
for key, value := range r.resources {
var values []string
for _, c := range value {
values = append(values, fmt.Sprintf("/%s/%s/%s", shared.APIVersion, key, c))
}
resources[key] = values
}
body.Resources = resources
}
w.Header().Set("Location", op)
w.WriteHeader(202)
return WriteJson(w, body)
}
func AsyncResponse(run func() shared.OperationResult, cancel func() error) Response {
return &asyncResponse{run: run, cancel: cancel}
}
func AsyncResponseWithWs(ws shared.OperationWebsocket, cancel func() error) Response {
return &asyncResponse{run: ws.Do, cancel: cancel, ws: ws}
}
type ErrorResponse struct {
code int
msg string
}
func (r *ErrorResponse) Render(w http.ResponseWriter) error {
var output io.Writer
buf := &bytes.Buffer{}
output = buf
var captured *bytes.Buffer
if *debug {
captured = &bytes.Buffer{}
output = io.MultiWriter(buf, captured)
}
err := json.NewEncoder(output).Encode(shared.Jmap{"type": lxd.Error, "error": r.msg, "error_code": r.code})
if err != nil {
return err
}
if *debug {
shared.DebugJson(captured)
}
http.Error(w, buf.String(), r.code)
return nil
}
/* Some standard responses */
var NotImplemented = &ErrorResponse{http.StatusNotImplemented, "not implemented"}
var NotFound = &ErrorResponse{http.StatusNotFound, "not found"}
var Forbidden = &ErrorResponse{http.StatusForbidden, "not authorized"}
var Conflict = &ErrorResponse{http.StatusConflict, "already exists"}
func BadRequest(err error) Response {
return &ErrorResponse{http.StatusBadRequest, err.Error()}
}
func InternalError(err error) Response {
return &ErrorResponse{http.StatusInternalServerError, err.Error()}
}
/*
* Write the right error message based on err.
*/
func SmartError(err error) Response {
switch err {
case os.ErrNotExist:
return NotFound
case sql.ErrNoRows:
return NotFound
case NoSuchImageError:
return NotFound
case os.ErrPermission:
return Forbidden
case DbErrAlreadyDefined:
return Conflict
case sqlite3.ErrConstraintUnique:
return Conflict
default:
return InternalError(err)
}
}