From 57e12f9a96f8e64410ac6b375a59b8adfcd0a390 Mon Sep 17 00:00:00 2001 From: BillyGriffiths <billy.griffiths@gmail.com> Date: Tue, 8 Nov 2022 12:18:06 +0200 Subject: [PATCH] Functions to allow for the conversion of x-www-form-urlencoded data to key value pairs and accessing them --- struct_utils/struct_utils.go | 39 ++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 struct_utils/struct_utils.go diff --git a/struct_utils/struct_utils.go b/struct_utils/struct_utils.go new file mode 100644 index 0000000..384feb3 --- /dev/null +++ b/struct_utils/struct_utils.go @@ -0,0 +1,39 @@ +package struct_utils + +import "strings" + +// KeyValuePair defines a key/value pair derived from form data +type KeyValuePair struct { + Key string `json:"key"` + Value string `json:"value"` +} + +// FormToKeyValuePairs returns a string-based map of strings as derived from posted form keys and values. +// e.g. oauth_consumer_key=mlhgs&oauth_consumer_secret=x240ar&oauth_verifier=b0qjbx&store_base_url=http%3A%2F%2Flocalhost.com%2Fstore +func FormToKeyValuePairs(body string) []KeyValuePair { + out := []KeyValuePair{} + parts := strings.Split(body, "&") + for _, p := range parts { + split := strings.Split(p, "=") + k := split[0] + v := split[1] + kv := KeyValuePair{ + Key: k, + Value: v, + } + out = append(out, kv) + } + + return out +} + +// GetValue returns the value for the given key from a KeyValuePair slice. +func GetValue(key string, kv []KeyValuePair) string { + for _, v := range kv { + if v.Key == key { + return v.Value + } + } + + return "" +} -- GitLab