diff --git a/README.md b/README.md index ad99be4..2b2e92d 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/encode.go b/encode.go index 57a0d0a..b310f9b 100644 --- a/encode.go +++ b/encode.go @@ -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 } diff --git a/form.go b/form.go index 4052369..0e9bdb8 100644 --- a/form.go +++ b/form.go @@ -11,4 +11,5 @@ const ( defaultDelimiter = '.' defaultEscape = '\\' + defaultKeepZeros = false )