diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..f69a9b4 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/valueextractor.iml b/.idea/valueextractor.iml new file mode 100644 index 0000000..5e764c4 --- /dev/null +++ b/.idea/valueextractor.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/converters.go b/converters.go index 6261de3..90fe9be 100644 --- a/converters.go +++ b/converters.go @@ -3,6 +3,7 @@ package valueextractor import ( "fmt" "strconv" + "strings" ) // Converter is a function that takes an Extractor and a key and returns a value and an error @@ -18,6 +19,17 @@ func ReturnString(ec *Extractor, key string) *string { return &s } +func ReturnStringArray(ec *Extractor, key string) *[]string { + var s []string + var str string + ec.With(key, AsString(&str)) + keys := strings.Split(str, ",") + for _, k := range keys { + s = append(s, k) + } + return &s +} + // AsString maintains the value as a string, just allowing extraction func AsString(ref *string) Converter { return func(ec *Extractor, value string) error { diff --git a/extractor_test.go b/extractor_test.go index 5d451aa..c56d7ab 100644 --- a/extractor_test.go +++ b/extractor_test.go @@ -72,8 +72,21 @@ func BenchmarkParamsParser(b *testing.B) { } } +// compareSlices compares two slices of strings and returns true if they are equal. +func compareSlices(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + func BenchmarkTypeReturn(b *testing.B) { - req, _ := http.NewRequest("GET", "http://localhost:8080?name=John&age=30", nil) + req, _ := http.NewRequest("GET", "http://localhost:8080?name=John&age=30&roles=hr,admin,super_admin", nil) for i := 0; i < b.N; i++ { ex := Using(QueryExtractor{Query: req.URL.Query()}) @@ -81,6 +94,10 @@ func BenchmarkTypeReturn(b *testing.B) { if *ReturnString(ex, "name") != "John" { b.Fatal("Name not parsed correctly") } + s := []string{"hr", "admin", "super_admin"} + if compareSlices(*ReturnStringArray(ex, "roles"), s) { + b.Fatal("roles not parsed correctly") + } if *ReturnUint64(ex, "age") != 30 { b.Fatal("Age not parsed correctly")