summaryrefslogtreecommitdiff
path: root/modules/caddyhttp/replacer.go
blob: 6a2ecd1852aeee1e4c25eaff0e1335523b2677f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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 = "{", "}"