summaryrefslogtreecommitdiff
path: root/modules/caddyhttp/replacer.go
diff options
context:
space:
mode:
authorMatthew Holt <mholt@users.noreply.github.com>2019-05-04 13:21:20 -0600
committerMatthew Holt <mholt@users.noreply.github.com>2019-05-04 13:21:20 -0600
commit2eb35933271d5b2ef1ca29aaa8f00f6748c56424 (patch)
tree480d08eb3f9b85353fb858d2b1b6c9cb86f33954 /modules/caddyhttp/replacer.go
parent1136e2cfeed5cc06a0811d39c2560c06f9dd74a2 (diff)
Begin implementing HTTP replacer and static responder
Diffstat (limited to 'modules/caddyhttp/replacer.go')
-rw-r--r--modules/caddyhttp/replacer.go75
1 files changed, 75 insertions, 0 deletions
diff --git a/modules/caddyhttp/replacer.go b/modules/caddyhttp/replacer.go
new file mode 100644
index 0000000..6a2ecd1
--- /dev/null
+++ b/modules/caddyhttp/replacer.go
@@ -0,0 +1,75 @@
+package caddyhttp
+
+import (
+ "net/http"
+ "strings"
+)
+
+type Replacer struct {
+ req *http.Request
+ resp http.ResponseWriter
+ custom map[string]string
+}
+
+// Map sets a custom variable mapping to a value.
+func (r *Replacer) Map(variable, value string) {
+ r.custom[variable] = value
+}
+
+// Replace replaces placeholders in input with the value. If
+// the value is empty string, the placeholder is substituted
+// with the value empty.
+func (r *Replacer) Replace(input, empty string) string {
+ if !strings.Contains(input, phOpen) {
+ return input
+ }
+
+ input = r.replaceAll(input, empty, r.defaults())
+ input = r.replaceAll(input, empty, r.custom)
+
+ return input
+}
+
+func (r *Replacer) replaceAll(input, empty string, mapping map[string]string) string {
+ for key, val := range mapping {
+ if val == "" {
+ val = empty
+ }
+ input = strings.ReplaceAll(input, phOpen+key+phClose, val)
+ }
+ return input
+}
+
+func (r *Replacer) defaults() map[string]string {
+ m := map[string]string{
+ "host": r.req.Host,
+ "method": r.req.Method,
+ "scheme": func() string {
+ if r.req.TLS != nil {
+ return "https"
+ }
+ return "http"
+ }(),
+ "uri": r.req.URL.RequestURI(),
+ }
+
+ for field, vals := range r.req.Header {
+ m[">"+strings.ToLower(field)] = strings.Join(vals, ",")
+ }
+
+ for field, vals := range r.resp.Header() {
+ m["<"+strings.ToLower(field)] = strings.Join(vals, ",")
+ }
+
+ for _, cookie := range r.req.Cookies() {
+ m["~"+cookie.Name] = cookie.Value
+ }
+
+ for param, vals := range r.req.URL.Query() {
+ m["?"+param] = strings.Join(vals, ",")
+ }
+
+ return m
+}
+
+const phOpen, phClose = "{", "}"