-
Notifications
You must be signed in to change notification settings - Fork 0
/
argsort.go
100 lines (87 loc) · 2.46 KB
/
argsort.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Package argsort provides a Caddy module that optionally lowercase and then sort the query arguments.
package argsort
import (
"net/http"
"net/url"
"strings"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
func init() {
caddy.RegisterModule(Argsort{})
httpcaddyfile.RegisterHandlerDirective("argsort", parseCaddyfile)
httpcaddyfile.RegisterDirectiveOrder("argsort", "before", "header")
}
// Argsort sort the query arguments after optionally lowercasing them.
//
// Syntax:
//
// argsort [lowercase]
type Argsort struct {
// Lowercase the query arguments before sorting them.
Lowercase bool `json:"lowercase,omitempty"`
}
// CaddyModule returns the Caddy module information.
func (Argsort) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.argsort",
New: func() caddy.Module { return new(Argsort) },
}
}
// Provision implements caddy.Provisioner.
func (a *Argsort) Provision(ctx caddy.Context) error {
return nil
}
// Validate implements caddy.Validator.
func (a *Argsort) Validate() error {
return nil
}
// ServeHTTP implements caddyhttp.MiddlewareHandler.
func (a Argsort) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
// url.Values.Encode() is doing the sort for us
if a.Lowercase {
values := url.Values{}
for k, s := range r.URL.Query() {
for _, v := range s {
values.Add(strings.ToLower(k), v)
}
}
r.URL.RawQuery = values.Encode()
} else {
r.URL.RawQuery = r.URL.Query().Encode()
}
return next.ServeHTTP(w, r)
}
// UnmarshalCaddyfile implements caddyfile.Unmarshaler.
// argsort [lower]
func (a *Argsort) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
// Set default value for Lower
a.Lowercase = false
for d.Next() {
if d.NextArg() {
if d.Val() == "lowercase" {
a.Lowercase = true
} else {
return d.ArgErr()
}
}
}
return nil
}
// parseCaddyfile sets up the handler from Caddyfile tokens. Syntax:
//
// argsort [lowecase]
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var a Argsort
err := a.UnmarshalCaddyfile(h.Dispenser)
return a, err
}
// Interface guards
var (
_ caddy.Provisioner = (*Argsort)(nil)
_ caddy.Validator = (*Argsort)(nil)
_ caddyhttp.MiddlewareHandler = (*Argsort)(nil)
_ caddyfile.Unmarshaler = (*Argsort)(nil)
)