Skip to content

Commit

Permalink
httpcaddyfile: Add 'vars' directive
Browse files Browse the repository at this point in the history
See discussion in #4650
  • Loading branch information
mholt committed Mar 22, 2022
1 parent 55b4c12 commit 79cbe7b
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 7 deletions.
8 changes: 8 additions & 0 deletions caddyconfig/httpcaddyfile/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func init() {
RegisterDirective("bind", parseBind)
RegisterDirective("tls", parseTLS)
RegisterHandlerDirective("root", parseRoot)
RegisterHandlerDirective("vars", parseVars)
RegisterHandlerDirective("redir", parseRedir)
RegisterHandlerDirective("respond", parseRespond)
RegisterHandlerDirective("abort", parseAbort)
Expand Down Expand Up @@ -530,6 +531,13 @@ func parseRoot(h Helper) (caddyhttp.MiddlewareHandler, error) {
return caddyhttp.VarsMiddleware{"root": root}, nil
}

// parseVars parses the vars directive. See its UnmarshalCaddyfile method for syntax.
func parseVars(h Helper) (caddyhttp.MiddlewareHandler, error) {
v := new(caddyhttp.VarsMiddleware)
err := v.UnmarshalCaddyfile(h.Dispenser)
return v, err
}

// parseRedir parses the redir directive. Syntax:
//
// redir [<matcher>] <to> [<code>]
Expand Down
1 change: 1 addition & 0 deletions caddyconfig/httpcaddyfile/directives.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ var directiveOrder = []string{
"tracing",

"map",
"vars",
"root",

"header",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ map {host} {my_placeholder} {magic_number} {
# Should output two strings, second being escaped quote
default "unknown domain" \"""
}

vars foo bar
vars {
abc true
def 1
ghi 2.3
jkl "mn op"
}
----------
{
"apps": {
Expand Down Expand Up @@ -91,6 +99,17 @@ map {host} {my_placeholder} {magic_number} {
}
],
"source": "{http.request.host}"
},
{
"foo": "bar",
"handler": "vars"
},
{
"abc": true,
"def": 1,
"ghi": 2.3,
"handler": "vars",
"jkl": "mn op"
}
]
}
Expand Down
66 changes: 59 additions & 7 deletions modules/caddyhttp/vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func init() {
//
// The key is the variable name, and the value is the value of the
// variable. Both the name and value may use or contain placeholders.
type VarsMiddleware map[string]string
type VarsMiddleware map[string]interface{}

// CaddyModule returns the Caddy module information.
func (VarsMiddleware) CaddyModule() caddy.ModuleInfo {
Expand All @@ -47,17 +47,67 @@ func (VarsMiddleware) CaddyModule() caddy.ModuleInfo {
}
}

func (t VarsMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error {
func (m VarsMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error {
vars := r.Context().Value(VarsCtxKey).(map[string]interface{})
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
for k, v := range t {
for k, v := range m {
keyExpanded := repl.ReplaceAll(k, "")
valExpanded := repl.ReplaceAll(v, "")
vars[keyExpanded] = valExpanded
if valStr, ok := v.(string); ok {
v = repl.ReplaceAll(valStr, "")
}
vars[keyExpanded] = v
}
return next.ServeHTTP(w, r)
}

// UnmarshalCaddyfile implements caddyfile.Unmarshaler. Syntax:
//
// vars [<name> <val>] {
// <name> <val>
// ...
// }
//
func (m *VarsMiddleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
if *m == nil {
*m = make(VarsMiddleware)
}

nextVar := func(headerLine bool) error {
if headerLine {
// header line is optional
if !d.NextArg() {
return nil
}
}
varName := d.Val()

if !d.NextArg() {
return d.ArgErr()
}
varValue := d.ScalarVal()

(*m)[varName] = varValue

if d.NextArg() {
return d.ArgErr()
}
return nil
}

for d.Next() {
if err := nextVar(true); err != nil {
return err
}
for nesting := d.Nesting(); d.NextBlock(nesting); {
if err := nextVar(false); err != nil {
return err
}
}
}

return nil
}

// VarsMatcher is an HTTP request matcher which can match
// requests based on variables in the context. The key is
// the name of the variable, and the values are possible
Expand Down Expand Up @@ -261,6 +311,8 @@ func SetVar(ctx context.Context, key string, value interface{}) {

// Interface guards
var (
_ MiddlewareHandler = (*VarsMiddleware)(nil)
_ RequestMatcher = (*VarsMatcher)(nil)
_ MiddlewareHandler = (*VarsMiddleware)(nil)
_ caddyfile.Unmarshaler = (*VarsMiddleware)(nil)
_ RequestMatcher = (*VarsMatcher)(nil)
_ caddyfile.Unmarshaler = (*VarsMatcher)(nil)
)

0 comments on commit 79cbe7b

Please sign in to comment.