| 1 | // Declare structures covering a subset of a HAR file |
| 2 | |
| 3 | struct HarContent { |
| 4 | size i64 |
| 5 | mime_type string @[json: 'mimeType'] |
| 6 | } |
| 7 | |
| 8 | struct HarResponse { |
| 9 | content HarContent |
| 10 | } |
| 11 | |
| 12 | struct HarEntry { |
| 13 | response HarResponse |
| 14 | } |
| 15 | |
| 16 | pub struct HarLog { |
| 17 | entries []HarEntry |
| 18 | } |
| 19 | |
| 20 | struct Har { |
| 21 | log HarLog |
| 22 | } |
| 23 | |
| 24 | // Declare function printing object contents using generics |
| 25 | |
| 26 | fn show[T](val T) { |
| 27 | $if T is string { |
| 28 | show_string(val) |
| 29 | } $else $if T is $array { |
| 30 | show_array(val) |
| 31 | } $else $if T is $struct { |
| 32 | show_struct(&val) |
| 33 | } $else { |
| 34 | print('primitive: ${val.str()}') |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | fn show_array[T](array []T) { |
| 39 | println('array []${T.name}') |
| 40 | for i, item in array { |
| 41 | println('item ${i}') |
| 42 | show(item) |
| 43 | println('') |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | fn show_struct[T](object &T) { |
| 48 | println('struct ${T.name}') |
| 49 | $for field in T.fields { |
| 50 | mut json_name := field.name |
| 51 | for attr in field.attrs { |
| 52 | if attr.starts_with('json: ') { |
| 53 | json_name = attr[6..] |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | print('key: ') |
| 58 | show_string(json_name) |
| 59 | println('') |
| 60 | |
| 61 | println('value ${T.name}.${field.name} (json: ${json_name}), field.typ: ${field.typ}') |
| 62 | $if field.typ is string { |
| 63 | print('string: ') |
| 64 | show_string(object.$(field.name)) |
| 65 | } $else $if field.is_array { |
| 66 | show_array(object.$(field.name)) |
| 67 | } $else $if field.is_struct { |
| 68 | item := object.$(field.name) |
| 69 | show_struct(&item) |
| 70 | } $else { |
| 71 | print('primitive: ') |
| 72 | print(object.$(field.name).str()) |
| 73 | } |
| 74 | println('') |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | fn show_string(s string) { |
| 79 | print(`"`) |
| 80 | print(s) |
| 81 | print(`"`) |
| 82 | } |
| 83 | |
| 84 | fn test_main() { |
| 85 | har := Har{ |
| 86 | log: HarLog{ |
| 87 | entries: [ |
| 88 | HarEntry{ |
| 89 | response: HarResponse{ |
| 90 | content: HarContent{ |
| 91 | size: 48752 |
| 92 | mime_type: 'text/html' |
| 93 | } |
| 94 | } |
| 95 | }, |
| 96 | ] |
| 97 | } |
| 98 | } |
| 99 | show(har) |
| 100 | assert true |
| 101 | } |
| 102 | |