■ ■ ■ ■ ■ ■
pkg/util/jsonlines/jsonlines.go
| 1 | + | package jsonlines |
| 2 | + | |
| 3 | + | import ( |
| 4 | + | "encoding/json" |
| 5 | + | "fmt" |
| 6 | + | "io" |
| 7 | + | "reflect" |
| 8 | + | |
| 9 | + | "github.com/bearer/bearer/pkg/util/linescanner" |
| 10 | + | ) |
| 11 | + | |
| 12 | + | const maxTokenSizeBytes int = 5 * 1024 * 1024 |
| 13 | + | |
| 14 | + | func getOriginalSlice(ptrToSlice interface{}) (slice reflect.Value, err error) { |
| 15 | + | ptr2sl := reflect.TypeOf(ptrToSlice) |
| 16 | + | if ptr2sl.Kind() != reflect.Ptr { |
| 17 | + | return reflect.ValueOf(nil), fmt.Errorf("expected pointer to slice, got %s", ptr2sl.Kind()) |
| 18 | + | } |
| 19 | + | |
| 20 | + | originalSlice := reflect.Indirect(reflect.ValueOf(ptrToSlice)) |
| 21 | + | sliceType := originalSlice.Type() |
| 22 | + | if sliceType.Kind() != reflect.Slice { |
| 23 | + | return reflect.ValueOf(nil), fmt.Errorf("expected pointer to slice, got pointer to %s", sliceType.Kind()) |
| 24 | + | } |
| 25 | + | return originalSlice, nil |
| 26 | + | } |
| 27 | + | |
| 28 | + | func Encode(w io.Writer, ptrToSlice interface{}) error { |
| 29 | + | slice, err := getOriginalSlice(ptrToSlice) |
| 30 | + | if err != nil { |
| 31 | + | return fmt.Errorf("wrong value inputed into jsonlines encode: %s", err) |
| 32 | + | } |
| 33 | + | |
| 34 | + | for i := 0; i < slice.Len(); i++ { |
| 35 | + | err := json.NewEncoder(w).Encode(slice.Index(i).Interface()) |
| 36 | + | if err != nil { |
| 37 | + | return fmt.Errorf("failed to encode json: %s", err) |
| 38 | + | } |
| 39 | + | } |
| 40 | + | |
| 41 | + | return nil |
| 42 | + | } |
| 43 | + | |
| 44 | + | func Decode(r io.Reader, ptrToSlice interface{}) error { |
| 45 | + | originalSlice, err := getOriginalSlice(ptrToSlice) |
| 46 | + | if err != nil { |
| 47 | + | return fmt.Errorf("wrong value inputed into jsonline decode: %s", err) |
| 48 | + | } |
| 49 | + | |
| 50 | + | scanner := linescanner.NewSize(r, maxTokenSizeBytes) |
| 51 | + | |
| 52 | + | member := originalSlice.Type().Elem() |
| 53 | + | |
| 54 | + | for { |
| 55 | + | ok := scanner.Scan() |
| 56 | + | if !ok { |
| 57 | + | break |
| 58 | + | } |
| 59 | + | |
| 60 | + | item := scanner.Bytes() |
| 61 | + | if len(item) == 0 { |
| 62 | + | continue |
| 63 | + | } |
| 64 | + | |
| 65 | + | newObj := reflect.New(member).Interface() |
| 66 | + | |
| 67 | + | err := json.Unmarshal(item, newObj) |
| 68 | + | if err != nil { |
| 69 | + | return fmt.Errorf("failed to unmarshal item: %s", err) |
| 70 | + | } |
| 71 | + | |
| 72 | + | ptrToNewObj := reflect.Indirect(reflect.ValueOf(newObj)) |
| 73 | + | originalSlice.Set(reflect.Append(originalSlice, ptrToNewObj)) |
| 74 | + | } |
| 75 | + | |
| 76 | + | return nil |
| 77 | + | } |
| 78 | + | |