-
Notifications
You must be signed in to change notification settings - Fork 51
/
response.go
211 lines (184 loc) · 6.14 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
// Copyright (c) 2014-2020 Canonical Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package daemon
import (
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"time"
"github.com/canonical/pebble/internals/logger"
)
type ResponseType string
const (
ResponseTypeSync ResponseType = "sync"
ResponseTypeAsync ResponseType = "async"
ResponseTypeError ResponseType = "error"
)
// Response knows how to serve itself, and how to find itself
type Response interface {
ServeHTTP(w http.ResponseWriter, r *http.Request)
}
type resp struct {
Status int `json:"status-code"`
Type ResponseType `json:"type"`
Change string `json:"change,omitempty"`
Result interface{} `json:"result,omitempty"`
WarningTimestamp *time.Time `json:"warning-timestamp,omitempty"`
WarningCount int `json:"warning-count,omitempty"`
Maintenance *errorResult `json:"maintenance,omitempty"`
}
type respJSON struct {
Type ResponseType `json:"type"`
Status int `json:"status-code"`
StatusText string `json:"status,omitempty"`
Change string `json:"change,omitempty"`
Result interface{} `json:"result,omitempty"`
WarningTimestamp *time.Time `json:"warning-timestamp,omitempty"`
WarningCount int `json:"warning-count,omitempty"`
Maintenance *errorResult `json:"maintenance,omitempty"`
}
func (r *resp) transmitMaintenance(kind errorKind, message string) {
r.Maintenance = &errorResult{
Kind: kind,
Message: message,
}
}
func (r *resp) addWarningsToMeta(count int, stamp time.Time) {
if r.WarningCount != 0 {
return
}
if count == 0 {
return
}
r.WarningCount = count
r.WarningTimestamp = &stamp
}
func (r *resp) MarshalJSON() ([]byte, error) {
return json.Marshal(respJSON{
Type: r.Type,
Status: r.Status,
StatusText: http.StatusText(r.Status),
Change: r.Change,
Result: r.Result,
WarningTimestamp: r.WarningTimestamp,
WarningCount: r.WarningCount,
Maintenance: r.Maintenance,
})
}
func (r *resp) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
status := r.Status
bs, err := r.MarshalJSON()
if err != nil {
logger.Noticef("Cannot marshal %#v to JSON: %v", *r, err)
bs = nil
status = http.StatusInternalServerError
}
hdr := w.Header()
if r.Status == http.StatusAccepted || r.Status == http.StatusCreated {
if m, ok := r.Result.(map[string]interface{}); ok {
if location, ok := m["resource"]; ok {
if location, ok := location.(string); ok && location != "" {
hdr.Set("Location", location)
}
}
}
}
hdr.Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write(bs)
}
type errorKind string
// Error kinds for use as a response or maintenance result
const (
errorKindLoginRequired = errorKind("login-required")
errorKindNoDefaultServices = errorKind("no-default-services")
errorKindNotFound = errorKind("not-found")
errorKindPermissionDenied = errorKind("permission-denied")
errorKindGenericFileError = errorKind("generic-file-error")
errorKindSystemRestart = errorKind("system-restart")
errorKindDaemonRestart = errorKind("daemon-restart")
)
type errorResult struct {
Message string `json:"message"` // note no omitempty
Kind errorKind `json:"kind,omitempty"`
Value interface{} `json:"value,omitempty"`
}
func SyncResponse(result interface{}) Response {
if err, ok := result.(error); ok {
return statusInternalError("internal error: %v", err)
}
if rsp, ok := result.(Response); ok {
return rsp
}
return &resp{
Type: ResponseTypeSync,
Status: http.StatusOK,
Result: result,
}
}
func AsyncResponse(result map[string]interface{}, change string) Response {
return &resp{
Type: ResponseTypeAsync,
Status: http.StatusAccepted,
Result: result,
Change: change,
}
}
// A fileResponse 's ServeHTTP method serves the file
type fileResponse string
// ServeHTTP from the Response interface
func (f fileResponse) ServeHTTP(w http.ResponseWriter, r *http.Request) {
filename := fmt.Sprintf("attachment; filename=%s", filepath.Base(string(f)))
w.Header().Add("Content-Disposition", filename)
http.ServeFile(w, r, string(f))
}
// ErrorResponse builds an error Response that returns the status and formatted message.
//
// If no arguments are provided, formatting is disabled, and the format string
// is used as is and not interpreted in any way.
func ErrorResponse(status int, format string, v ...interface{}) Response {
res := &errorResult{}
if len(v) == 0 {
res.Message = format
} else {
res.Message = fmt.Sprintf(format, v...)
}
if status == http.StatusUnauthorized {
res.Kind = errorKindLoginRequired
}
return &resp{
Type: ResponseTypeError,
Result: res,
Status: status,
}
}
func makeErrorResponder(status int) errorResponder {
return func(format string, v ...interface{}) Response {
return ErrorResponse(status, format, v...)
}
}
// errorResponder is a callable that produces an error Response.
// e.g., InternalError("something broke: %v", err), etc.
type errorResponder func(string, ...interface{}) Response
// Standard error responses.
var (
statusBadRequest = makeErrorResponder(http.StatusBadRequest)
statusUnauthorized = makeErrorResponder(http.StatusUnauthorized)
statusForbidden = makeErrorResponder(http.StatusForbidden)
statusNotFound = makeErrorResponder(http.StatusNotFound)
statusMethodNotAllowed = makeErrorResponder(http.StatusMethodNotAllowed)
statusInternalError = makeErrorResponder(http.StatusInternalServerError)
statusGatewayTimeout = makeErrorResponder(http.StatusGatewayTimeout)
)