Skip to content

Commit faa69f4

Browse files
committed
allow custom delimiter for slices and arrays
Fixes #32
1 parent 2c9db42 commit faa69f4

File tree

2 files changed

+35
-7
lines changed

2 files changed

+35
-7
lines changed

query/encode.go

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,13 @@ type Encoder interface {
9494
// Including the "brackets" option signals that the multiple URL values should
9595
// have "[]" appended to the value name. "numbered" will append a number to
9696
// the end of each incidence of the value name, example:
97-
// name0=value0&name1=value1, etc.
97+
// name0=value0&name1=value1, etc. Including the "del" struct tag (separate
98+
// from the "url" tag) will use the value of the "del" tag as the delimiter.
99+
// For example:
100+
//
101+
// // Encode a slice of bools as ints ("1" for true, "0" for false),
102+
// // separated by exclamation points "!".
103+
// Field []bool `url:",int" del:"!"`
98104
//
99105
// Anonymous struct fields are usually encoded as if their inner exported
100106
// fields were fields in the outer struct, subject to the standard Go
@@ -192,25 +198,27 @@ func reflectValue(values url.Values, val reflect.Value, scope string) error {
192198
}
193199

194200
if sv.Kind() == reflect.Slice || sv.Kind() == reflect.Array {
195-
var del byte
201+
var del string
196202
if opts.Contains("comma") {
197-
del = ','
203+
del = ","
198204
} else if opts.Contains("space") {
199-
del = ' '
205+
del = " "
200206
} else if opts.Contains("semicolon") {
201-
del = ';'
207+
del = ";"
202208
} else if opts.Contains("brackets") {
203209
name = name + "[]"
210+
} else {
211+
del = sf.Tag.Get("del")
204212
}
205213

206-
if del != 0 {
214+
if del != "" {
207215
s := new(bytes.Buffer)
208216
first := true
209217
for i := 0; i < sv.Len(); i++ {
210218
if first {
211219
first = false
212220
} else {
213-
s.WriteByte(del)
221+
s.WriteString(del)
214222
}
215223
s.WriteString(valueString(sv.Index(i), opts))
216224
}

query/encode_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,26 @@ func TestValues_Slices(t *testing.T) {
212212
url.Values{"V0": {"a"}, "V1": {"b"}},
213213
},
214214

215+
// custom delimeters
216+
{
217+
struct {
218+
V []string `del:","`
219+
}{[]string{"a", "b"}},
220+
url.Values{"V": {"a,b"}},
221+
},
222+
{
223+
struct {
224+
V []string `del:"|"`
225+
}{[]string{"a", "b"}},
226+
url.Values{"V": {"a|b"}},
227+
},
228+
{
229+
struct {
230+
V []string `del:"🥑"`
231+
}{[]string{"a", "b"}},
232+
url.Values{"V": {"a🥑b"}},
233+
},
234+
215235
// slice of bools with additional options
216236
{
217237
struct {

0 commit comments

Comments
 (0)