diff options
author | Ethel Morgan <eth@ethulhu.co.uk> | 2020-07-07 16:23:16 +0100 |
---|---|---|
committer | Ethel Morgan <eth@ethulhu.co.uk> | 2020-07-07 16:23:16 +0100 |
commit | 268a9deb94231b81e91f28da5658b4330953a3cf (patch) | |
tree | 11743e15295f6ce1982ba622a9af02ec7dee8719 /formvalues.go | |
parent | 977df56847fb57ca128df82614798b3301d3dfd6 (diff) |
import FormValues github.com/gorilla/mux MatcherFuncv0.0.3
Diffstat (limited to 'formvalues.go')
-rw-r--r-- | formvalues.go | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/formvalues.go b/formvalues.go new file mode 100644 index 0000000..359e513 --- /dev/null +++ b/formvalues.go @@ -0,0 +1,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 + } +} |