UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: intercept [<matcher>] { # intercept original responses @name { status <code...> header <field> [<value>] } replace_status [<matcher>] <status_code> handle_response [<matcher>] {
(d *caddyfile.Dispenser)
| 224 | // |
| 225 | // EXPERIMENTAL: Subject to change or removal. |
| 226 | func (i *Intercept) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { |
| 227 | // collect the response matchers defined as subdirectives |
| 228 | // prefixed with "@" for use with "handle_response" blocks |
| 229 | i.responseMatchers = make(map[string]caddyhttp.ResponseMatcher) |
| 230 | |
| 231 | d.Next() // consume the directive name |
| 232 | for d.NextBlock(0) { |
| 233 | // if the subdirective has an "@" prefix then we |
| 234 | // parse it as a response matcher for use with "handle_response" |
| 235 | if strings.HasPrefix(d.Val(), matcherPrefix) { |
| 236 | err := caddyhttp.ParseNamedResponseMatcher(d.NewFromNextSegment(), i.responseMatchers) |
| 237 | if err != nil { |
| 238 | return err |
| 239 | } |
| 240 | continue |
| 241 | } |
| 242 | |
| 243 | switch d.Val() { |
| 244 | case "handle_response": |
| 245 | // delegate the parsing of handle_response to the caller, |
| 246 | // since we need the httpcaddyfile.Helper to parse subroutes. |
| 247 | // See h.FinalizeUnmarshalCaddyfile |
| 248 | i.handleResponseSegments = append(i.handleResponseSegments, d.NewFromNextSegment()) |
| 249 | |
| 250 | case "replace_status": |
| 251 | args := d.RemainingArgs() |
| 252 | if len(args) != 1 && len(args) != 2 { |
| 253 | return d.Errf("must have one or two arguments: an optional response matcher, and a status code") |
| 254 | } |
| 255 | |
| 256 | responseHandler := caddyhttp.ResponseHandler{} |
| 257 | |
| 258 | if len(args) == 2 { |
| 259 | if !strings.HasPrefix(args[0], matcherPrefix) { |
| 260 | return d.Errf("must use a named response matcher, starting with '@'") |
| 261 | } |
| 262 | foundMatcher, ok := i.responseMatchers[args[0]] |
| 263 | if !ok { |
| 264 | return d.Errf("no named response matcher defined with name '%s'", args[0][1:]) |
| 265 | } |
| 266 | responseHandler.Match = &foundMatcher |
| 267 | responseHandler.StatusCode = caddyhttp.WeakString(args[1]) |
| 268 | } else if len(args) == 1 { |
| 269 | responseHandler.StatusCode = caddyhttp.WeakString(args[0]) |
| 270 | } |
| 271 | |
| 272 | // make sure there's no block, cause it doesn't make sense |
| 273 | if nesting := d.Nesting(); d.NextBlock(nesting) { |
| 274 | return d.Errf("cannot define routes for 'replace_status', use 'handle_response' instead.") |
| 275 | } |
| 276 | |
| 277 | i.HandleResponse = append( |
| 278 | i.HandleResponse, |
| 279 | responseHandler, |
| 280 | ) |
| 281 | |
| 282 | default: |
| 283 | return d.Errf("unrecognized subdirective %s", d.Val()) |
no test coverage detected