Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,29 @@ While encouraged, it is not necessary to define a type (e.g. a `struct`) in orde

By default, and without custom marshaling, zero values (also known as empty/default values) are encoded as the empty string. To disable this behavior, meaning to keep zero values in their literal form (e.g. `0` for integral types), `Encoder` offers a `KeepZeros` setter method, which will do just that when set to `true`.

For instance, given...

```go
foo := map[string]interface{}{"b": false, "i": 0}
```

...the following...

```go
form.EncodeToString(foo) // i.e. keepZeros == false
```

...will result in `"b=&i="`, whereas...

```go
keepZeros := true
delimiter := '.'
escape := '\\'
form.EncodeToStringWith(foo, delimiter, escape, keepZeros)
```

...will result in `"b=false&i=0"`.

### Unsupported Values

Values of the following kinds aren't supported and, if present, must be ignored.
Expand Down
18 changes: 14 additions & 4 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,23 +67,33 @@ func (e Encoder) Encode(dst interface{}) error {

// EncodeToString encodes dst as a form and returns it as a string.
func EncodeToString(dst interface{}) (string, error) {
return EncodeToStringWith(dst, defaultDelimiter, defaultEscape, defaultKeepZeros)
}

// EncodeToStringWith encodes dst as a form with delimiter d, escape e, keeping zero values if z, and returns it as a string.
func EncodeToStringWith(dst interface{}, d rune, e rune, z bool) (string, error) {
v := reflect.ValueOf(dst)
n, err := encodeToNode(v, false)
n, err := encodeToNode(v, z)
if err != nil {
return "", err
}
vs := n.values(defaultDelimiter, defaultEscape)
vs := n.values(d, e)
return vs.Encode(), nil
}

// EncodeToValues encodes dst as a form and returns it as Values.
func EncodeToValues(dst interface{}) (url.Values, error) {
return EncodeToValuesWith(dst, defaultDelimiter, defaultEscape, defaultKeepZeros)
}

// EncodeToValuesWith encodes dst as a form with delimiter d, escape e, keeping zero values if z, and returns it as Values.
func EncodeToValuesWith(dst interface{}, d rune, e rune, z bool) (url.Values, error) {
v := reflect.ValueOf(dst)
n, err := encodeToNode(v, false)
n, err := encodeToNode(v, z)
if err != nil {
return nil, err
}
vs := n.values(defaultDelimiter, defaultEscape)
vs := n.values(d, e)
return vs, nil
}

Expand Down
1 change: 1 addition & 0 deletions form.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ const (

defaultDelimiter = '.'
defaultEscape = '\\'
defaultKeepZeros = false
)