Skip to content

Commit

Permalink
use regex instead
Browse files Browse the repository at this point in the history
  • Loading branch information
sarge committed Mar 27, 2020
1 parent 5bf624c commit a542d45
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 21 deletions.
4 changes: 2 additions & 2 deletions caddytest/integration/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ func TestMap(t *testing.T) {
http_port 9080
https_port 9443
}
localhost:9080 {
map http.request.method dest-name {
default unknown
GET get-called
G.T get-called
POST post-called
}
Expand Down
35 changes: 16 additions & 19 deletions modules/caddyhttp/map/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package mmap

import (
"net/http"
"regexp"

"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
Expand All @@ -33,7 +34,6 @@ type Handler struct {
Destination string `json:"destination,omitempty"`
Default string `json:"default,omitempty"`
Items []Item `json:"items,omitempty"`
internalMap map[string]string
}

// CaddyModule returns the Caddy module information.
Expand All @@ -46,22 +46,14 @@ func (Handler) CaddyModule() caddy.ModuleInfo {

// Provision -
func (h *Handler) Provision(_ caddy.Context) error {
h.internalMap = make(map[string]string)
return nil
}

// Validate ensures h's configuration is valid.
func (h Handler) Validate() error {

//TODO: detect and compile regular expressions
//TODO: organise a data structure to determine the order in which
// the static keys and regular expressions can be deterministically
// evaluated. Static keys first then regular expressions in order?
// Or evaluated in order of appearance?

// load the values
for _, v := range h.Items {
h.internalMap[v.Key] = v.Value
for i := 0; i < len(h.Items); i++ {
h.Items[i].compiled = regexp.MustCompile(h.Items[i].Key)
}
return nil
}
Expand All @@ -71,18 +63,21 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhtt

// get the source value, if the source value was not found do no
// replacement.
//TODO: has the potential to miss changes in variables made later
// in the request pipeline but perhaps that is a simplier mental
// model to start with.
val, ok := repl.Get(h.Source)
if ok {
v, ok := h.internalMap[val]
if !ok && h.Default != "" {
v = h.Default
found := false
for i := 0; i < len(h.Items); i++ {
if h.Items[i].compiled.Match([]byte(val)) {
found = true
repl.Set(h.Destination, h.Items[i].Value)
break
}
}
repl.Set(h.Destination, v)
}

if !found && h.Default != "" {
repl.Set(h.Destination, h.Default)
}
}
return next.ServeHTTP(w, r)
}

Expand All @@ -92,6 +87,8 @@ type Item struct {
Key string `json:"key,omitempty"`
// Value
Value string `json:"value,omitempty"`
// compiled internal value
compiled *regexp.Regexp
}

// Interface guards
Expand Down

0 comments on commit a542d45

Please sign in to comment.