Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ToQuery and FromQuery #417

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
39 changes: 39 additions & 0 deletions conversion.go
@@ -0,0 +1,39 @@
package lo

import (
"fmt"
"strings"
)

// form query convert string to query string
func ToQuery[K comparable, V any](in map[K]V) string {
res := ""

firstIteration := true
for k, v := range in {
if firstIteration {
res += fmt.Sprintf("%v=%v", k, v)
firstIteration = false
} else {
res += fmt.Sprintf("&%v=%v", k, v)
}
}

return res
}

// form query convert query string to string
func FromQuery(s string) map[string]string {
result := make(map[string]string)

pairs := strings.Split(s, "&")

for _, pair := range pairs {
parts := strings.Split(pair, "=")
if len(parts) == 2 {
result[parts[0]] = parts[1]
}
}

return result
}
33 changes: 33 additions & 0 deletions conversion_test.go
@@ -0,0 +1,33 @@
package lo

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestToQuery(t *testing.T) {
t.Parallel()
is := assert.New(t)

result1 := ToQuery(map[string]string{"foo": "bar", "bar": "baz", "k": "v"})
result2 := ToQuery(map[string]string{"foo": "bar", "bar": "baz"})
result3 := ToQuery(map[string]string{"key": "value"})

is.Equal(result1, "foo=bar&bar=baz&k=v")
is.Equal(result2, "foo=bar&bar=baz")
is.Equal(result3, "key=value")
}

func TestFromQuery(t *testing.T) {
t.Parallel()
is := assert.New(t)

result1 := FromQuery("foo=bar&bar=baz&k=v")
result2 := FromQuery("foo=bar&bar=baz")
result3 := FromQuery("key=value")

is.Equal(result1, map[string]string{"foo": "bar", "bar": "baz", "k": "v"})
is.Equal(result2, map[string]string{"foo": "bar", "bar": "baz"})
is.Equal(result3, map[string]string{"key": "value"})
}