-
Notifications
You must be signed in to change notification settings - Fork 10
/
gocnab.go
606 lines (505 loc) · 18 KB
/
gocnab.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
// Package gocnab implements encoding and decoding of CNAB (Centro Nacional de
// Automação Bancária) as defined by FEBRABAN (Federação Brasileira de Bancos).
package gocnab
import (
"bytes"
"encoding"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
)
// LineBreak defines the control characters at the end of each registry entry.
// It should be the hex encoded 0D0A except for the last one.
const LineBreak = "\r\n"
// FinalControlCharacter defines the control character of the last registry
// entry. It should be the hex encoded 1A.
const FinalControlCharacter = "\x1A"
var (
// ErrUnsupportedType raised when trying to marshal something different from a
// struct or a slice.
ErrUnsupportedType = errors.New("gocnab: unsupported type")
// ErrInvalidFieldTagFormat CNAB field tag doesn't follow the expected format.
ErrInvalidFieldTagFormat = errors.New("invalid field tag format")
// ErrInvalidFieldTagBeginRange begin range isn't a valid number in the CNAB
// tag.
ErrInvalidFieldTagBeginRange = errors.New("invalid begin range in cnab tag")
// ErrInvalidFieldTagEndRange end range isn't a valid number in the CNAB tag.
ErrInvalidFieldTagEndRange = errors.New("invalid end range in cnab tag")
// ErrInvalidFieldTagRange ranges don't have consistency with the desired
// encoding in the CNAB tag.
ErrInvalidFieldTagRange = errors.New("invalid range in cnab tag")
)
// MarshalOptions contains available options when marshaling. The properties can
// be modified using auxiliary functions directly into the marshal calls.
//
// Example:
//
// Marshal240(myCNABType, gocnab.WithFinalControlCharacter(false))
type MarshalOptions struct {
addFinalControlCharacter bool
}
// MarshalOptionFunc helper type alias to handle options.
type MarshalOptionFunc func(*MarshalOptions)
// WithFinalControlCharacter allows to enable or disable the final control
// character. The first version of this library was designed to build valid CNAB
// files for Bradesco bank, and one of Bradesco's requirements was to contain
// the final control hexadecimal character 1A. But as this library started being
// used by other integrations, the final control character became an issue, as
// it doesn't comply with other specifications. By default, the final control
// character is added to keep backward compatibility.
func WithFinalControlCharacter(enabled bool) MarshalOptionFunc {
return MarshalOptionFunc(func(options *MarshalOptions) {
options.addFinalControlCharacter = enabled
})
}
// Marshal150 returns the CNAB 150 encoding of vs. The accepted types are struct
// and slice of struct, where only the exported struct fields with the tag
// "cnab" are going to be used. Invalid cnab tag ranges will generate errors.
//
// The following struct field types are supported: string, bool, int, int8,
// int16, int32, int64, uint, uint8, uint16, uint23, uint64, float32, float64,
// gocnab.Marshaler and encoding.TextMarshaler. Where string are transformed to
// uppercase and are left aligned in the CNAB space, booleans are represented as
// 1 or 0, numbers are right aligned with zeros and float decimal separators are
// removed.
//
// When only one parameter is given the generated CNAB line will only have break
// line symbols if the input is a slice of struct. When using multiple
// parameters the library determinate that you are trying to build the full CNAB
// file, so it add the breaking lines and the final control symbol.
func Marshal150(vs ...interface{}) ([]byte, error) {
return marshal(150, vs...)
}
// Marshal240 returns the CNAB 240 encoding of vs. The accepted types are struct
// and slice of struct, where only the exported struct fields with the tag
// "cnab" are going to be used. Invalid cnab tag ranges will generate errors.
//
// The following struct field types are supported: string, bool, int, int8,
// int16, int32, int64, uint, uint8, uint16, uint23, uint64, float32, float64,
// gocnab.Marshaler and encoding.TextMarshaler. Where string are transformed to
// uppercase and are left aligned in the CNAB space, booleans are represented as
// 1 or 0, numbers are right aligned with zeros and float decimal separators are
// removed.
//
// When only one parameter is given the generated CNAB line will only have break
// line symbols if the input is a slice of struct. When using multiple
// parameters the library determinate that you are trying to build the full CNAB
// file, so it add the breaking lines and the final control symbol.
func Marshal240(vs ...interface{}) ([]byte, error) {
return marshal(240, vs...)
}
// Marshal400 returns the CNAB 400 encoding of vs. The accepted types are struct
// and slice of struct, where only the exported struct fields with the tag
// "cnab" are going to be used. Invalid cnab tag ranges will generate errors.
//
// The following struct field types are supported: string, bool, int, int8,
// int16, int32, int64, uint, uint8, uint16, uint23, uint64, float32, float64,
// gocnab.Marshaler and encoding.TextMarshaler. Where string are transformed to
// uppercase and are left aligned in the CNAB space, booleans are represented as
// 1 or 0, numbers are right aligned with zeros and float decimal separators are
// removed.
//
// When only one parameter is given the generated CNAB line will only have break
// line symbols if the input is a slice of struct. When using multiple
// parameters the library determinate that you are trying to build the full CNAB
// file, so it add the breaking lines and the final control symbol.
func Marshal400(vs ...interface{}) ([]byte, error) {
return marshal(400, vs...)
}
// Marshal500 returns the CNAB 500 encoding of vs. The accepted types are struct
// and slice of struct, where only the exported struct fields with the tag
// "cnab" are going to be used. Invalid cnab tag ranges will generate errors.
//
// The following struct field types are supported: string, bool, int, int8,
// int16, int32, int64, uint, uint8, uint16, uint23, uint64, float32, float64,
// gocnab.Marshaler and encoding.TextMarshaler. Where string are transformed to
// uppercase and are left aligned in the CNAB space, booleans are represented as
// 1 or 0, numbers are right aligned with zeros and float decimal separators are
// removed.
//
// When only one parameter is given the generated CNAB line will only have break
// line symbols if the input is a slice of struct. When using multiple
// parameters the library determinate that you are trying to build the full CNAB
// file, so it add the breaking lines and the final control symbol.
func Marshal500(vs ...interface{}) ([]byte, error) {
return marshal(500, vs...)
}
func marshal(lineSize int, vs ...interface{}) ([]byte, error) {
options := MarshalOptions{
addFinalControlCharacter: true,
}
var i int
for _, v := range vs {
if optFunc, ok := v.(MarshalOptionFunc); ok {
optFunc(&options)
} else {
vs[i] = v
i++
}
}
vs = vs[:i]
var cnab []byte
for i, v := range vs {
cnabLine, err := marshalLine(lineSize, v)
if err != nil {
return nil, err
}
cnab = append(cnab, cnabLine...)
// don't add line break symbol to the last line
if len(vs) > 1 && i < len(vs)-1 {
cnab = append(cnab, []byte(LineBreak)...)
}
}
if options.addFinalControlCharacter && len(vs) > 1 && cnab != nil {
cnab = append(cnab, []byte(FinalControlCharacter)...)
}
return cnab, nil
}
func marshalLine(lineSize int, v interface{}) ([]byte, error) {
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Struct:
cnab := []byte(strings.Repeat(" ", lineSize))
if err := marshalStruct(cnab, rv); err != nil {
return nil, err
}
return cnab, nil
case reflect.Slice:
var cnab []byte
for i := 0; i < rv.Len(); i++ {
line := []byte(strings.Repeat(" ", lineSize))
if err := marshalStruct(line, rv.Index(i)); err != nil {
return nil, err
}
cnab = append(cnab, line...)
// don't add line break symbol to the last line
if i < rv.Len()-1 {
cnab = append(cnab, []byte(LineBreak)...)
}
}
return cnab, nil
}
return nil, ErrUnsupportedType
}
func marshalStruct(data []byte, v reflect.Value) error {
structType := v.Type()
for i := 0; i < structType.NumField(); i++ {
structField := structType.Field(i)
begin, end, err := parseCNABFieldTag(structField, len(data))
if err != nil {
return FieldError{
Field: structField.Name,
Err: err,
}
}
// ignore fields without range
if begin == 0 && end == 0 {
continue
}
if err = marshalField(data, v.FieldByName(structField.Name), begin, end); err != nil {
return FieldError{
Field: structField.Name,
Err: err,
}
}
}
return nil
}
func marshalField(data []byte, v reflect.Value, begin, end int) error {
cnabFieldSize := end - begin
switch v.Kind() {
case reflect.String:
fieldContent := v.Interface().(string)
setFieldContent(data, fieldContent, begin, end)
return nil
case reflect.Bool:
fieldContent := v.Interface().(bool)
var convertedFieldContent string
if fieldContent {
convertedFieldContent = "1"
} else {
convertedFieldContent = "0"
}
convertedFieldContent = fmt.Sprintf("%0"+strconv.Itoa(cnabFieldSize)+"s", convertedFieldContent)
setFieldContent(data, convertedFieldContent, begin, end)
return nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fieldContent := fmt.Sprintf("%0"+strconv.Itoa(cnabFieldSize)+"d", v.Int())
setFieldContent(data, fieldContent, begin, end)
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
fieldContent := fmt.Sprintf("%0"+strconv.Itoa(cnabFieldSize)+"d", v.Uint())
setFieldContent(data, fieldContent, begin, end)
return nil
case reflect.Float32, reflect.Float64:
// replace decimal separator for nothing and add an extra 0 to fill the gap
fieldContent := fmt.Sprintf("%0"+strconv.Itoa(cnabFieldSize)+".2f", v.Float())
fieldContent = "0" + strings.Replace(fieldContent, ".", "", -1)
setFieldContent(data, fieldContent, begin, end)
return nil
}
marshalerType := reflect.TypeOf((*Marshaler)(nil)).Elem()
if v.Type().Implements(marshalerType) {
fieldContent, err := v.Interface().(Marshaler).MarshalCNAB()
if err != nil {
return err
}
setFieldContent(data, string(fieldContent), begin, end)
return nil
}
textMarshalerType := reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
if v.Type().Implements(textMarshalerType) {
fieldContent, err := v.Interface().(encoding.TextMarshaler).MarshalText()
if err != nil {
return err
}
setFieldContent(data, string(fieldContent), begin, end)
return nil
}
return ErrUnsupportedType
}
func setFieldContent(data []byte, fieldContent string, begin, end int) {
cnabFieldSize := end - begin
// strip field if is too big for the space
if len(fieldContent) > cnabFieldSize {
fieldContent = fieldContent[0:cnabFieldSize]
} else if len(fieldContent) < cnabFieldSize {
fieldContent = fieldContent + strings.Repeat(" ", cnabFieldSize-len(fieldContent))
}
copy(data[begin:], strings.ToUpper(fieldContent))
}
// Unmarshal parses the CNAB-encoded data and stores the result in the value
// pointed to by v. Accepted types of v are: *struct, *[]struct or
// map[string]interface{}.
//
// The following struct field types are supported: string, bool, int, int8,
// int16, int32, int64, uint, uint8, uint16, uint23, uint64, float32, float64,
// gocnab.Unmarshaler and encoding.TextUnmarshaler.
//
// When parsing a full CNAB file we recommend using the map type (mapper) to
// fill different lines into the correct types. Usually the CNAB prefix
// determinate the type used, so the mapper key will be the prefix, and the
// mapper value is the pointer to the type that you're filling. For example, if
// we have a CNAB file where the starter character determinate the type, and for
// "0" is header, "1" is the content line (can repeat many times) and "2" is the
// footer, we could have the following code to unmarshal:
//
// header := struct{ A int `cnab:1,10` }{}
// content := []struct{ B string `cnab:1,10` }{}
// footer := struct{ C bool `cnab:1,2` }{}
//
// cnab.Unmarshal(data, map[string]interface{}{
// "0": &header,
// "1": &content,
// "2": &footer,
// })
func Unmarshal(data []byte, v interface{}) error {
rv := reflect.ValueOf(v)
if (rv.Kind() != reflect.Ptr && rv.Kind() != reflect.Map) || rv.IsNil() {
return ErrUnsupportedType
}
if rv.Kind() == reflect.Ptr {
rvElem := rv.Elem()
switch rvElem.Kind() {
case reflect.Struct:
return unmarshalStruct(data, rvElem)
case reflect.Slice:
return unmarshalSlice(data, rvElem)
}
}
if mapper, ok := v.(map[string]interface{}); ok {
return unmarshalMapper(data, mapper)
}
return ErrUnsupportedType
}
func unmarshalMapper(data []byte, mapper map[string]interface{}) error {
cnabLinesGroupBy := make(map[string][]byte)
cnabLines := bytes.Split(data, []byte(LineBreak))
for _, cnabLine := range cnabLines {
if len(cnabLine) == 0 {
continue
}
for id := range mapper {
if !bytes.HasPrefix(cnabLine, []byte(id)) {
continue
}
if _, ok := cnabLinesGroupBy[id]; ok {
cnabLinesGroupBy[id] = append(cnabLinesGroupBy[id], []byte(LineBreak)...)
}
cnabLinesGroupBy[id] = append(cnabLinesGroupBy[id], cnabLine...)
}
}
for id, lines := range cnabLinesGroupBy {
if err := Unmarshal(lines, mapper[id]); err != nil {
return err
}
}
return nil
}
func unmarshalSlice(data []byte, v reflect.Value) error {
sliceType := v.Type().Elem()
if sliceType.Kind() != reflect.Struct {
return ErrUnsupportedType
}
cnabLines := bytes.Split(data, []byte(LineBreak))
for _, cnabLine := range cnabLines {
if len(cnabLine) == 0 {
continue
}
itemValue := reflect.New(sliceType)
if err := unmarshalStruct(cnabLine, itemValue.Elem()); err != nil {
return err
}
v.Set(reflect.Append(v, itemValue.Elem()))
}
return nil
}
func unmarshalStruct(data []byte, v reflect.Value) error {
structType := v.Type()
for i := 0; i < structType.NumField(); i++ {
structField := structType.Field(i)
begin, end, err := parseCNABFieldTag(structField, len(data))
if err != nil {
return FieldError{
Field: structField.Name,
Err: err,
}
}
// ignore fields without range or not exported
field := v.FieldByName(structField.Name)
if (begin == 0 && end == 0) || !field.CanSet() {
continue
}
if err = unmarshalField(data, field, begin, end); err != nil {
return UnmarshalFieldError{
Field: structField.Name,
Data: data[begin:end],
Err: err,
}
}
}
return nil
}
func unmarshalField(data []byte, v reflect.Value, begin, end int) error {
cnabFieldStr := string(data[begin:end])
cnabFieldStr = strings.TrimSpace(cnabFieldStr)
switch v.Kind() {
case reflect.String:
v.SetString(cnabFieldStr)
return nil
case reflect.Bool:
boolNumber, err := strconv.ParseInt(cnabFieldStr, 10, 64)
if err != nil {
return err
}
v.SetBool(boolNumber != 0)
return nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
number, err := strconv.ParseInt(cnabFieldStr, 10, 64)
if err != nil {
return err
}
v.SetInt(number)
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
number, err := strconv.ParseUint(cnabFieldStr, 10, 64)
if err != nil {
return err
}
v.SetUint(number)
return nil
case reflect.Float32, reflect.Float64:
numberRaw := cnabFieldStr
// add again the dot before converting to float64
if len(numberRaw) > 2 {
numberRaw = numberRaw[:len(numberRaw)-2] + "." + numberRaw[len(numberRaw)-2:]
} else {
numberRaw = "0." + numberRaw
}
number, err := strconv.ParseFloat(string(numberRaw), 64)
if err != nil {
return err
}
v.SetFloat(number)
return nil
}
if v.CanAddr() {
unmarshalerType := reflect.TypeOf((*Unmarshaler)(nil)).Elem()
if v.Addr().Type().Implements(unmarshalerType) {
return v.Addr().Interface().(Unmarshaler).UnmarshalCNAB(data[begin:end])
}
textUnmarshalerType := reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
if v.Addr().Type().Implements(textUnmarshalerType) {
return v.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText(data[begin:end])
}
}
return ErrUnsupportedType
}
func parseCNABFieldTag(structField reflect.StructField, dataSize int) (begin int, end int, err error) {
cnabFieldOptionsRaw := structField.Tag.Get("cnab")
if cnabFieldOptionsRaw == "" {
return 0, 0, nil
}
cnabFieldOptions := strings.Split(cnabFieldOptionsRaw, ",")
if len(cnabFieldOptions) != 2 {
return 0, 0, ErrInvalidFieldTagFormat
}
begin, err = strconv.Atoi(cnabFieldOptions[0])
if err != nil {
return 0, 0, ErrInvalidFieldTagBeginRange
}
end, err = strconv.Atoi(cnabFieldOptions[1])
if err != nil {
return 0, 0, ErrInvalidFieldTagEndRange
}
if begin < 0 || end < begin || end > dataSize {
return 0, 0, ErrInvalidFieldTagRange
}
return
}
// Marshaler is the interface implemented by types that can marshal themselves
// into valid string representation.
type Marshaler interface {
MarshalCNAB() ([]byte, error)
}
// Unmarshaler is the interface implemented by types that can unmarshal a string
// representation description of themselves. UnmarshalCNAB must copy the CNAB
// data if it wishes to retain the data after returning.
type Unmarshaler interface {
UnmarshalCNAB([]byte) error
}
// FieldError problem detected in a field tag containing CNAB options or when
// marshalling the field itself.
type FieldError struct {
Field string
Err error
}
// Error return a human readable representation of the field error.
func (f FieldError) Error() string {
errStr := "<nil>"
if f.Err != nil {
errStr = f.Err.Error()
}
return fmt.Sprintf("gocnab: error in field %s. details: %s", f.Field, errStr)
}
// UnmarshalFieldError stores the error that occurred while decoding the CNAB
// data into a field.
type UnmarshalFieldError struct {
Field string
Data []byte
Err error
}
// Error return a human readable representation of the unmarshal error.
func (u UnmarshalFieldError) Error() string {
dataStr := "<nil>"
if u.Data != nil {
dataStr = string(u.Data)
}
errStr := "<nil>"
if u.Err != nil {
errStr = u.Err.Error()
}
return fmt.Sprintf("gocnab: error unmarshaling in field %s with data “%s”. details: %s", u.Field, dataStr, errStr)
}