/
response.go
195 lines (159 loc) · 4.49 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/lxc/lxd"
"github.com/lxc/lxd/shared"
)
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 (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}
enc, err := json.Marshal(&resp)
if err != nil {
return err
}
_, err = w.Write(enc)
return err
}
/*
* 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
containers []string
done chan shared.OperationResult
}
func (r *asyncResponse) Render(w http.ResponseWriter) error {
op, err := CreateOperation(nil, 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()
}
if r.containers != nil && len(r.containers) > 0 {
body.Resources = map[string][]string{}
var containers []string
for _, c := range r.containers {
containers = append(containers, fmt.Sprintf("/%s/containers/%s", shared.APIVersion, c))
}
body.Resources["containers"] = containers
}
w.Header().Set("Location", op)
w.WriteHeader(202)
return json.NewEncoder(w).Encode(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 {
buf := bytes.Buffer{}
err := json.NewEncoder(&buf).Encode(shared.Jmap{"type": lxd.Error, "error": r.msg, "error_code": r.code})
if err != nil {
return err
}
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 os.ErrPermission:
return Forbidden
default:
return InternalError(err)
}
}