diff options
| author | Francis Lavoie <lavofr@gmail.com> | 2021-03-12 15:25:49 -0500 | 
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-03-12 13:25:49 -0700 | 
| commit | 0d7fe36007d5fbadaa6057b6543500d63147e6c0 (patch) | |
| tree | 748b591a07fecede95e5fdcca0a53e93010c9af6 /modules/caddyhttp/staticerror.go | |
| parent | f137b82227f7b32b2ca036a89068c806a29a5ac7 (diff) | |
httpcaddyfile: Add `error` directive for the existing handler (#4034)
* httpcaddyfile: Add `error` directive for the existing handler
* httpcaddyfile: Move `error` to the end of the order
Diffstat (limited to 'modules/caddyhttp/staticerror.go')
| -rw-r--r-- | modules/caddyhttp/staticerror.go | 50 | 
1 files changed, 49 insertions, 1 deletions
| diff --git a/modules/caddyhttp/staticerror.go b/modules/caddyhttp/staticerror.go index d2d255e..914e6c1 100644 --- a/modules/caddyhttp/staticerror.go +++ b/modules/caddyhttp/staticerror.go @@ -20,6 +20,7 @@ import (  	"strconv"  	"github.com/caddyserver/caddy/v2" +	"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"  )  func init() { @@ -50,6 +51,50 @@ func (StaticError) CaddyModule() caddy.ModuleInfo {  	}  } +// UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: +// +//     error [<matcher>] <status>|<message> [<status>] { +//         message <text> +//     } +// +// If there is just one argument (other than the matcher), it is considered +// to be a status code if it's a valid positive integer of 3 digits. +func (e *StaticError) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { +	for d.Next() { +		args := d.RemainingArgs() +		switch len(args) { +		case 1: +			if len(args[0]) == 3 { +				if num, err := strconv.Atoi(args[0]); err == nil && num > 0 { +					e.StatusCode = WeakString(args[0]) +					break +				} +			} +			e.Error = args[0] +		case 2: +			e.Error = args[0] +			e.StatusCode = WeakString(args[1]) +		default: +			return d.ArgErr() +		} + +		for d.NextBlock(0) { +			switch d.Val() { +			case "message": +				if e.Error != "" { +					return d.Err("message already specified") +				} +				if !d.AllArgs(&e.Error) { +					return d.ArgErr() +				} +			default: +				return d.Errf("unrecognized subdirective '%s'", d.Val()) +			} +		} +	} +	return nil +} +  func (e StaticError) ServeHTTP(w http.ResponseWriter, r *http.Request, _ Handler) error {  	repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) @@ -66,4 +111,7 @@ func (e StaticError) ServeHTTP(w http.ResponseWriter, r *http.Request, _ Handler  }  // Interface guard -var _ MiddlewareHandler = (*StaticError)(nil) +var ( +	_ MiddlewareHandler     = (*StaticError)(nil) +	_ caddyfile.Unmarshaler = (*StaticError)(nil) +) | 
