Skip to content

Commit 7431e1b

Browse files
author
Dean Karn
authored
Added urlext.TestEncodeToURLValues helper (#5)
1 parent 4a4788a commit 7431e1b

File tree

4 files changed

+41
-1
lines changed

4 files changed

+41
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# pkg
2-
![Project status](https://img.shields.io/badge/version-5.0.0-green.svg)
2+
![Project status](https://img.shields.io/badge/version-5.1.0-green.svg)
33
[![Build Status](https://travis-ci.org/go-playground/pkg.svg?branch=master)](https://travis-ci.org/go-playground/pkg)
44
[![Coverage Status](https://coveralls.io/repos/github/go-playground/pkg/badge.svg?branch=master)](https://coveralls.io/github/go-playground/pkg?branch=master)
55
[![GoDoc](https://godoc.org/github.com/go-playground/pkg?status.svg)](https://pkg.go.dev/mod/github.com/go-playground/pkg/v5)

net/http/form.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,15 @@ type FormDecoder interface {
1111
Decode(interface{}, url.Values) error
1212
}
1313

14+
// FormEncoder is the type used for encoding form data
15+
type FormEncoder interface {
16+
Encode(interface{}) (url.Values, error)
17+
}
18+
1419
var (
1520
// DefaultFormDecoder of this package, which is configurable
1621
DefaultFormDecoder FormDecoder = form.NewDecoder()
22+
23+
// DefaultFormEncoder of this package, which is configurable
24+
DefaultFormEncoder FormEncoder = form.NewEncoder()
1725
)

net/url/helpers.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package urlext
2+
3+
import (
4+
"net/url"
5+
6+
httpext "github.com/go-playground/pkg/v5/net/http"
7+
)
8+
9+
// EncodeToURLValues encodes a struct or field into a set of url.Values
10+
func EncodeToURLValues(v interface{}) (url.Values, error) {
11+
return httpext.DefaultFormEncoder.Encode(v)
12+
}

net/url/helpers_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package urlext
2+
3+
import (
4+
"testing"
5+
6+
. "github.com/go-playground/assert/v2"
7+
)
8+
9+
func TestEncodeToURLValues(t *testing.T) {
10+
type Test struct {
11+
Domain string `form:"domain"`
12+
Next string `form:"next"`
13+
}
14+
15+
s := Test{Domain: "company.org", Next: "NIDEJ89#(@#NWJK"}
16+
values, err := EncodeToURLValues(s)
17+
Equal(t, err, nil)
18+
Equal(t, len(values), 2)
19+
Equal(t, values.Encode(), "domain=company.org&next=NIDEJ89%23%28%40%23NWJK")
20+
}

0 commit comments

Comments
 (0)