@@ -20,16 +20,32 @@ import (
2020var encoders sync.Map // map[encoderEntry]encoderFunc
2121
2222func Marshal (value interface {}, writer * multipart.Writer ) error {
23- e := & encoder {dateFormat : time .RFC3339 }
23+ e := & encoder {
24+ dateFormat : time .RFC3339 ,
25+ arrayFmt : "brackets" ,
26+ }
2427 return e .marshal (value , writer )
2528}
2629
2730func MarshalRoot (value interface {}, writer * multipart.Writer ) error {
28- e := & encoder {root : true , dateFormat : time .RFC3339 }
31+ e := & encoder {
32+ root : true ,
33+ dateFormat : time .RFC3339 ,
34+ arrayFmt : "brackets" ,
35+ }
36+ return e .marshal (value , writer )
37+ }
38+
39+ func MarshalWithSettings (value interface {}, writer * multipart.Writer , arrayFormat string ) error {
40+ e := & encoder {
41+ arrayFmt : arrayFormat ,
42+ dateFormat : time .RFC3339 ,
43+ }
2944 return e .marshal (value , writer )
3045}
3146
3247type encoder struct {
48+ arrayFmt string
3349 dateFormat string
3450 root bool
3551}
@@ -163,15 +179,40 @@ func (e *encoder) newPrimitiveTypeEncoder(t reflect.Type) encoderFunc {
163179 }
164180}
165181
182+ func arrayKeyEncoder (arrayFmt string ) func (string , int ) string {
183+ var keyFn func (string , int ) string
184+ switch arrayFmt {
185+ case "comma" , "repeat" :
186+ keyFn = func (k string , _ int ) string { return k }
187+ case "brackets" :
188+ keyFn = func (key string , _ int ) string { return key + "[]" }
189+ case "indices:dots" :
190+ keyFn = func (k string , i int ) string {
191+ if k == "" {
192+ return strconv .Itoa (i )
193+ }
194+ return k + "." + strconv .Itoa (i )
195+ }
196+ case "indices:brackets" :
197+ keyFn = func (k string , i int ) string {
198+ if k == "" {
199+ return strconv .Itoa (i )
200+ }
201+ return k + "[" + strconv .Itoa (i ) + "]"
202+ }
203+ }
204+ return keyFn
205+ }
206+
166207func (e * encoder ) newArrayTypeEncoder (t reflect.Type ) encoderFunc {
167208 itemEncoder := e .typeEncoder (t .Elem ())
168-
209+ keyFn := arrayKeyEncoder ( e . arrayFmt )
169210 return func (key string , v reflect.Value , writer * multipart.Writer ) error {
170- if key != "" {
171- key = key + "."
211+ if keyFn == nil {
212+ return fmt . Errorf ( "apiform: unsupported array format" )
172213 }
173214 for i := 0 ; i < v .Len (); i ++ {
174- err := itemEncoder (key + strconv . Itoa ( i ), v .Index (i ), writer )
215+ err := itemEncoder (keyFn ( key , i ), v .Index (i ), writer )
175216 if err != nil {
176217 return err
177218 }
0 commit comments