fork of indigo with slightly nicer lexgen
at main 1.1 kB view raw
1package data 2 3import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8) 9 10// Helper type for extracting record $type from CBOR 11type GenericRecord struct { 12 Type string `json:"$type" cborgen:"$type"` 13} 14 15// Parses the top-level $type field from generic atproto JSON data 16func ExtractTypeJSON(b []byte) (string, error) { 17 var gr GenericRecord 18 if err := json.Unmarshal(b, &gr); err != nil { 19 return "", err 20 } 21 22 return gr.Type, nil 23} 24 25// Parses the top-level $type field from generic atproto CBOR data 26func ExtractTypeCBOR(b []byte) (string, error) { 27 var gr GenericRecord 28 if err := gr.UnmarshalCBOR(bytes.NewReader(b)); err != nil { 29 fmt.Printf("bad bytes: %x\n", b) 30 return "", err 31 } 32 33 return gr.Type, nil 34} 35 36// Parses top-level $type field from generic atproto CBOR. 37// 38// Returns that string field, and additional bytes (TODO: the parsed bytes, or remaining bytes?) 39func ExtractTypeCBORReader(r io.Reader) (string, []byte, error) { 40 buf := new(bytes.Buffer) 41 tr := io.TeeReader(r, buf) 42 var gr GenericRecord 43 if err := gr.UnmarshalCBOR(tr); err != nil { 44 return "", nil, err 45 } 46 47 return gr.Type, buf.Bytes(), nil 48}