forked from moov-io/iso8583
-
Notifications
You must be signed in to change notification settings - Fork 0
/
describe.go
104 lines (81 loc) · 2.05 KB
/
describe.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
package iso8583
import (
"encoding/hex"
"fmt"
"io"
"sort"
"strings"
"text/tabwriter"
"github.com/moov-io/iso8583/field"
)
var defaultSpecName = "ISO 8583"
func Describe(message *Message, w io.Writer, filters ...FieldFilter) error {
specName := defaultSpecName
if spec := message.GetSpec(); spec != nil && spec.Name != "" {
specName = spec.Name
}
fmt.Fprintf(w, "%s Message:\n", specName)
tw := tabwriter.NewWriter(w, 0, 0, 3, '.', 0)
mti, err := message.GetMTI()
if err != nil {
return fmt.Errorf("getting MTI: %w", err)
}
fmt.Fprintf(tw, "MTI\t: %s\n", mti)
bitmapRaw, err := message.Bitmap().Bytes()
if err != nil {
return fmt.Errorf("getting bitmap bytes: %w", err)
}
fmt.Fprintf(tw, "Bitmap\t: %s\n", strings.ToUpper(hex.EncodeToString(bitmapRaw)))
bitmap, err := message.Bitmap().String()
if err != nil {
return fmt.Errorf("getting bitmap: %w", err)
}
fmt.Fprintf(tw, "Bitmap bits\t: %s\n", bitmap)
// display the rest of all set fields
fields := message.GetFields()
// use default filter
if len(filters) == 0 {
filters = DefaultFilters()
}
// making filter map
filterMap := make(map[int]FilterFunc)
for _, filter := range filters {
filter(filterMap)
}
var errorList []string
for _, i := range sortFieldIDs(fields) {
// skip the bitmap
if i == 1 {
continue
}
field := fields[i]
desc := field.Spec().Description
str, err := field.String()
if err != nil {
errorList = append(errorList, err.Error())
continue
}
// apply filtering
if filter, existed := filterMap[i]; existed {
str = filter(str, fields[i])
}
fmt.Fprintf(tw, fmt.Sprintf("F%03d %s\t: %%s\n", i, desc), str)
}
tw.Flush()
if len(errorList) > 0 {
fmt.Fprintf(w, "\nUnpacking Errors:\n")
for _, err := range errorList {
fmt.Fprintf(w, "- %s:\n", err)
}
return fmt.Errorf("displaying fields: %s", strings.Join(errorList, ","))
}
return nil
}
func sortFieldIDs(fields map[int]field.Field) []int {
keys := make([]int, 0, len(fields))
for k := range fields {
keys = append(keys, k)
}
sort.Ints(keys)
return keys
}