Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 13, 16:45 UTC
admin: Implement /adapt endpoint (close #4465) (#4846)
Matt Holt committed
Jun 28, 2022 at 22:43 UTC
660c59b6f3c138ce1a143ea864225ba177005e8e
1 file changed
+46
-1
caddyconfig/load.go
+46
-1
@@ -58,6 +58,10 @@ func (al adminLoad) Routes() []caddy.AdminRoute {
58
Pattern: "/load",
59
Handler: caddy.AdminHandlerFunc(al.handleLoad),
60
},
61
+ {
62
+ Pattern: "/adapt",
63
+ Handler: caddy.AdminHandlerFunc(al.handleAdapt),
64
+ },
65
}
66
}
67
@@ -122,7 +126,48 @@ func (adminLoad) handleLoad(w http.ResponseWriter, r *http.Request) error {
126
return nil
127
}
128
125
-// adaptByContentType adapts body to Caddy JSON using the adapter specified by contenType.
129
+// handleAdapt adapts the given Caddy config to JSON and responds with the result.
130
+func (adminLoad) handleAdapt(w http.ResponseWriter, r *http.Request) error {
131
+ if r.Method != http.MethodPost {
132
+ return caddy.APIError{
133
+ HTTPStatus: http.StatusMethodNotAllowed,
134
+ Err: fmt.Errorf("method not allowed"),
135
+ }
136
+ }
137
+
138
+ buf := bufPool.Get().(*bytes.Buffer)
139
+ buf.Reset()
140
+ defer bufPool.Put(buf)
141
+
142
+ _, err := io.Copy(buf, r.Body)
143
+ if err != nil {
144
+ return caddy.APIError{
145
+ HTTPStatus: http.StatusBadRequest,
146
+ Err: fmt.Errorf("reading request body: %v", err),
147
+ }
148
+ }
149
+
150
+ result, warnings, err := adaptByContentType(r.Header.Get("Content-Type"), buf.Bytes())
151
+ if err != nil {
152
+ return caddy.APIError{
153
+ HTTPStatus: http.StatusBadRequest,
154
+ Err: err,
155
+ }
156
+ }
157
+
158
+ out := struct {
159
+ Warnings []Warning `json:"warnings,omitempty"`
160
+ Result json.RawMessage `json:"result"`
161
+ }{
162
+ Warnings: warnings,
163
+ Result: result,
164
+ }
165
+
166
+ w.Header().Set("Content-Type", "application/json")
167
+ return json.NewEncoder(w).Encode(out)
168
+}
169
+
170
+// adaptByContentType adapts body to Caddy JSON using the adapter specified by contentType.
171
// If contentType is empty or ends with "/json", the input will be returned, as a no-op.
172
func adaptByContentType(contentType string, body []byte) ([]byte, []Warning, error) {
173
// assume JSON as the default