summaryrefslogtreecommitdiff
path: root/formvalues.go
blob: 359e513a001de2059bee35a0332128cb55c2c63c (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
// SPDX-FileCopyrightText: 2020 Ethel Morgan
//
// SPDX-License-Identifier: MIT

package httputil

import (
	"net/http"
	"strings"

	"github.com/gorilla/mux"
)

// FormValues matches POST form values the same way that github.com/gorilla/mux's built-in Queries and Headers does.
func FormValues(keysAndValues ...string) mux.MatcherFunc {
	if len(keysAndValues)%2 != 0 {
		panic("an equal number of keys and values must be provided")
	}
	return func(r *http.Request, rm *mux.RouteMatch) bool {
		for i := 0; i < len(keysAndValues); i += 2 {
			key := keysAndValues[i]
			value := keysAndValues[i+1]

			formValue := r.FormValue(key)
			if formValue == "" {
				return false
			}

			if strings.HasPrefix(value, "{") && strings.HasSuffix(value, "}") {
				if rm.Vars == nil {
					rm.Vars = map[string]string{}
				}
				varKey := value[1 : len(value)-1]
				rm.Vars[varKey] = formValue
			} else {
				if formValue != value {
					return false
				}
			}
		}
		return true
	}
}