Package cbor is a modern CBOR codec (RFC 8949 & RFC 8742) with CBOR tags, Go struct tag options (toarray/keyasint/omitempty/omitzero), Core Deterministic Encoding, CTAP2, Canonical CBOR, float64->32->16, and duplicate map key detection.
Encoding options allow "preferred serialization" by encoding integers and floats to their smallest forms (e.g. float16) when values fit.
Struct tag options "keyasint", "toarray", "omitempty", and "omitzero" reduce encoding size and reduce programming effort.
For example, "toarray" tag makes struct fields encode to CBOR array elements. And "keyasint" makes a field encode to an element of CBOR map with specified int key.
Latest docs can be viewed at https://github.com/fxamacker/cbor#cbor-library-in-go
Basics ¶The Quick Start guide is at https://github.com/fxamacker/cbor#quick-start
Function signatures identical to encoding/json include:
Marshal, Unmarshal, NewEncoder, NewDecoder, (*Encoder).Encode, (*Decoder).Decode
Standard interfaces include:
BinaryMarshaler, BinaryUnmarshaler, Marshaler, and Unmarshaler
Diagnostic functions translate CBOR data item into Diagnostic Notation:
Diagnose, DiagnoseFirst
Functions that simplify using CBOR Sequences (RFC 8742) include:
UnmarshalFirst
Custom encoding and decoding is possible by implementing standard interfaces for user-defined Go types.
Codec functions are available at package-level (using defaults options) or by creating modes from options at runtime.
"Mode" in this API means definite way of encoding (EncMode) or decoding (DecMode).
EncMode and DecMode interfaces are created from EncOptions or DecOptions structs.
em, err := cbor.EncOptions{...}.EncMode() em, err := cbor.CanonicalEncOptions().EncMode() em, err := cbor.CTAP2EncOptions().EncMode()
Modes use immutable options to avoid side-effects and simplify concurrency. Behavior of modes won't accidentally change at runtime after they're created.
Modes are intended to be reused and are safe for concurrent use.
EncMode and DecMode Interfaces
// EncMode interface uses immutable options and is safe for concurrent use. type EncMode interface { Marshal(v interface{}) ([]byte, error) NewEncoder(w io.Writer) *Encoder EncOptions() EncOptions // returns copy of options } // DecMode interface uses immutable options and is safe for concurrent use. type DecMode interface { Unmarshal(data []byte, v interface{}) error NewDecoder(r io.Reader) *Decoder DecOptions() DecOptions // returns copy of options }
Using Default Encoding Mode
b, err := cbor.Marshal(v) encoder := cbor.NewEncoder(w) err = encoder.Encode(v)
Using Default Decoding Mode
err := cbor.Unmarshal(b, &v) decoder := cbor.NewDecoder(r) err = decoder.Decode(&v)
Using Default Mode of UnmarshalFirst to Decode CBOR Sequences
// Decode the first CBOR data item and return remaining bytes: rest, err = cbor.UnmarshalFirst(b, &v) // decode []byte b to v
Using Extended Diagnostic Notation (EDN) to represent CBOR data
// Translate the first CBOR data item into text and return remaining bytes. text, rest, err = cbor.DiagnoseFirst(b) // decode []byte b to text
Creating and Using Encoding Modes
// Create EncOptions using either struct literal or a function. opts := cbor.CanonicalEncOptions() // If needed, modify encoding options opts.Time = cbor.TimeUnix // Create reusable EncMode interface with immutable options, safe for concurrent use. em, err := opts.EncMode() // Use EncMode like encoding/json, with same function signatures. b, err := em.Marshal(v) // or encoder := em.NewEncoder(w) err := encoder.Encode(v) // NOTE: Both em.Marshal(v) and encoder.Encode(v) use encoding options // specified during creation of em (encoding mode).CBOR Options ¶
Predefined Encoding Options: https://github.com/fxamacker/cbor#predefined-encoding-options
Encoding Options: https://github.com/fxamacker/cbor#encoding-options
Decoding Options: https://github.com/fxamacker/cbor#decoding-options
Struct Tags ¶Struct tags like `cbor:"name,omitempty"` and `json:"name,omitempty"` work as expected. If both struct tags are specified then `cbor` is used.
Struct tag options like "keyasint", "toarray", "omitempty", and "omitzero" make it easy to use very compact formats like COSE and CWT (CBOR Web Tokens) with structs.
The "omitzero" option omits zero values from encoding, matching [stdlib encoding/json behavior](https://pkg.go.dev/encoding/json#Marshal). When specified in the `cbor` tag, the option is always honored. When specified in the `json` tag, the option is honored when building with Go 1.24+.
For example, "toarray" makes struct fields encode to array elements. And "keyasint" makes struct fields encode to elements of CBOR map with int keys.
https://raw.githubusercontent.com/fxamacker/images/master/cbor/v2.0.0/cbor_easy_api.png
Struct tag options are listed at https://github.com/fxamacker/cbor#struct-tags-1
Tests and Fuzzing ¶Over 375 tests are included in this package. Cover-guided fuzzing is handled by a private fuzzer that replaced fxamacker/cbor-fuzz years ago.
// Use "keyasint" struct tag option to encode/decode struct to/from CBOR map. // Use cbor.RawMessage to delay unmarshaling (CrvOrNOrK's data type depends on Kty's value). type coseKey struct { Kty int `cbor:"1,keyasint,omitempty"` Kid []byte `cbor:"2,keyasint,omitempty"` Alg int `cbor:"3,keyasint,omitempty"` KeyOpts int `cbor:"4,keyasint,omitempty"` IV []byte `cbor:"5,keyasint,omitempty"` CrvOrNOrK cbor.RawMessage `cbor:"-1,keyasint,omitempty"` // K for symmetric keys, Crv for elliptic curve keys, N for RSA modulus XOrE cbor.RawMessage `cbor:"-2,keyasint,omitempty"` // X for curve x-coordinate, E for RSA public exponent Y cbor.RawMessage `cbor:"-3,keyasint,omitempty"` // Y for curve y-coordinate D []byte `cbor:"-4,keyasint,omitempty"` } // Data from https://tools.ietf.org/html/rfc8392#appendix-A section A.2 // 128-Bit Symmetric Key data, _ := hex.DecodeString("a42050231f4c4d4d3051fdc2ec0a3851d5b3830104024c53796d6d6574726963313238030a") var v coseKey if err := cbor.Unmarshal(data, &v); err != nil { fmt.Println("error:", err) } if _, err := cbor.Marshal(v); err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", v)
Output: {Kty:4 Kid:[83 121 109 109 101 116 114 105 99 49 50 56] Alg:10 KeyOpts:0 IV:[] CrvOrNOrK:[80 35 31 76 77 77 48 81 253 194 236 10 56 81 213 179 131] XOrE:[] Y:[] D:[]}
// Use "keyasint" struct tag option to encode/decode struct to/from CBOR map. type claims struct { Iss string `cbor:"1,keyasint"` Sub string `cbor:"2,keyasint"` Aud string `cbor:"3,keyasint"` Exp int `cbor:"4,keyasint"` Nbf int `cbor:"5,keyasint"` Iat int `cbor:"6,keyasint"` Cti []byte `cbor:"7,keyasint"` } // Data from https://tools.ietf.org/html/rfc8392#appendix-A section A.1 data, _ := hex.DecodeString("a70175636f61703a2f2f61732e6578616d706c652e636f6d02656572696b77037818636f61703a2f2f6c696768742e6578616d706c652e636f6d041a5612aeb0051a5610d9f0061a5610d9f007420b71") var v claims if err := cbor.Unmarshal(data, &v); err != nil { fmt.Println("error:", err) } if _, err := cbor.Marshal(v); err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", v)
Output: {Iss:coap://as.example.com Sub:erikw Aud:coap://light.example.com Exp:1444064944 Nbf:1443944944 Iat:1443944944 Cti:[11 113]}
type claims struct { Iss string `cbor:"1,keyasint"` Sub string `cbor:"2,keyasint"` Aud string `cbor:"3,keyasint"` Exp int `cbor:"4,keyasint"` Nbf int `cbor:"5,keyasint"` Iat int `cbor:"6,keyasint"` Cti []byte `cbor:"7,keyasint"` } // Data from https://tools.ietf.org/html/rfc8392#appendix-A section A.1 data, _ := hex.DecodeString("a70175636f61703a2f2f61732e6578616d706c652e636f6d02656572696b77037818636f61703a2f2f6c696768742e6578616d706c652e636f6d041a5612aeb0051a5610d9f0061a5610d9f007420b71") dm, _ := cbor.DecOptions{DupMapKey: cbor.DupMapKeyEnforcedAPF}.DecMode() var v claims if err := dm.Unmarshal(data, &v); err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", v)
Output: {Iss:coap://as.example.com Sub:erikw Aud:coap://light.example.com Exp:1444064944 Nbf:1443944944 Iat:1443944944 Cti:[11 113]}
package main // fxamacker/cbor allows user apps to use almost any current or future // CBOR tag number by implementing cbor.Marshaler and cbor.Unmarshaler // interfaces. Essentially, MarshalCBOR and UnmarshalCBOR functions that // are implemented by user apps will automatically be called by this // CBOR codec's Marshal, Unmarshal, etc. // // This example shows how to encode and decode a tagged CBOR data item with // tag number 262 and the tag content is a JSON object "embedded" as a // CBOR byte string (major type 2). // // NOTE: RFC 8949 does not mention tag number 262. IANA assigned // CBOR tag number 262 as "Embedded JSON Object" specified by the // document Embedded JSON Tag for CBOR: // // "Tag 262 can be applied to a byte string (major type 2) to indicate // that the byte string is a JSON Object. The length of the byte string // indicates the content." // // For more info, see Embedded JSON Tag for CBOR at: // https://github.com/toravir/CBOR-Tag-Specs/blob/master/embeddedJSON.md import ( "bytes" "encoding/json" "fmt" "github.com/fxamacker/cbor/v2" ) // cborTagNumForEmbeddedJSON is the CBOR tag number 262. const cborTagNumForEmbeddedJSON = 262 // EmbeddedJSON represents a Go value to be encoded as a tagged CBOR data item // with tag number 262 and the tag content is a JSON object "embedded" as a // CBOR byte string (major type 2). type EmbeddedJSON struct { any } func NewEmbeddedJSON(val any) EmbeddedJSON { return EmbeddedJSON{val} } // MarshalCBOR encodes EmbeddedJSON to a tagged CBOR data item with the // tag number 262 and the tag content is a JSON object that is // "embedded" as a CBOR byte string. func (v EmbeddedJSON) MarshalCBOR() ([]byte, error) { // Encode v to JSON object. data, err := json.Marshal(v) if err != nil { return nil, err } // Create cbor.Tag representing a tagged CBOR data item. tag := cbor.Tag{ Number: cborTagNumForEmbeddedJSON, Content: data, } // Marshal to a tagged CBOR data item. return cbor.Marshal(tag) } // UnmarshalCBOR decodes a tagged CBOR data item to EmbeddedJSON. // The byte slice provided to this function must contain a single // tagged CBOR data item with the tag number 262 and tag content // must be a JSON object "embedded" as a CBOR byte string. func (v *EmbeddedJSON) UnmarshalCBOR(b []byte) error { // Unmarshal tagged CBOR data item. var tag cbor.Tag if err := cbor.Unmarshal(b, &tag); err != nil { return err } // Check tag number. if tag.Number != cborTagNumForEmbeddedJSON { return fmt.Errorf("got tag number %d, expect tag number %d", tag.Number, cborTagNumForEmbeddedJSON) } // Check tag content. jsonData, isByteString := tag.Content.([]byte) if !isByteString { return fmt.Errorf("got tag content type %T, expect tag content []byte", tag.Content) } // Unmarshal JSON object. return json.Unmarshal(jsonData, v) } // MarshalJSON encodes EmbeddedJSON to a JSON object. func (v EmbeddedJSON) MarshalJSON() ([]byte, error) { return json.Marshal(v.any) } // UnmarshalJSON decodes a JSON object. func (v *EmbeddedJSON) UnmarshalJSON(b []byte) error { dec := json.NewDecoder(bytes.NewReader(b)) dec.UseNumber() return dec.Decode(&v.any) } func main() { value := NewEmbeddedJSON(map[string]any{ "name": "gopher", "id": json.Number("42"), }) data, err := cbor.Marshal(value) if err != nil { panic(err) } fmt.Printf("cbor: %x\n", data) var v EmbeddedJSON err = cbor.Unmarshal(data, &v) if err != nil { panic(err) } fmt.Printf("%+v\n", v.any) for k, v := range v.any.(map[string]any) { fmt.Printf(" %s: %v (%T)\n", k, v, v) } }
// Use "keyasint" struct tag option to encode/decode struct to/from CBOR map. type SenMLRecord struct { BaseName string `cbor:"-2,keyasint,omitempty"` BaseTime float64 `cbor:"-3,keyasint,omitempty"` BaseUnit string `cbor:"-4,keyasint,omitempty"` BaseValue float64 `cbor:"-5,keyasint,omitempty"` BaseSum float64 `cbor:"-6,keyasint,omitempty"` BaseVersion int `cbor:"-1,keyasint,omitempty"` Name string `cbor:"0,keyasint,omitempty"` Unit string `cbor:"1,keyasint,omitempty"` Time float64 `cbor:"6,keyasint,omitempty"` UpdateTime float64 `cbor:"7,keyasint,omitempty"` Value float64 `cbor:"2,keyasint,omitempty"` ValueS string `cbor:"3,keyasint,omitempty"` ValueB bool `cbor:"4,keyasint,omitempty"` ValueD string `cbor:"8,keyasint,omitempty"` Sum float64 `cbor:"5,keyasint,omitempty"` } // Data from https://tools.ietf.org/html/rfc8428#section-6 data, _ := hex.DecodeString("87a721781b75726e3a6465763a6f773a3130653230373361303130383030363a22fb41d303a15b00106223614120050067766f6c7461676501615602fb405e066666666666a3006763757272656e74062402fb3ff3333333333333a3006763757272656e74062302fb3ff4cccccccccccda3006763757272656e74062202fb3ff6666666666666a3006763757272656e74062102f93e00a3006763757272656e74062002fb3ff999999999999aa3006763757272656e74060002fb3ffb333333333333") var v []*SenMLRecord if err := cbor.Unmarshal(data, &v); err != nil { fmt.Println("error:", err) } // Encoder uses ShortestFloat16 option to use float16 as the shortest form that preserves floating-point value. em, err := cbor.EncOptions{ShortestFloat: cbor.ShortestFloat16}.EncMode() if err != nil { fmt.Println("error:", err) } if _, err := em.Marshal(v); err != nil { fmt.Println("error:", err) } for _, rec := range v { fmt.Printf("%+v\n", *rec) }
Output: {BaseName:urn:dev:ow:10e2073a0108006: BaseTime:1.276020076001e+09 BaseUnit:A BaseValue:0 BaseSum:0 BaseVersion:5 Name:voltage Unit:V Time:0 UpdateTime:0 Value:120.1 ValueS: ValueB:false ValueD: Sum:0} {BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:-5 UpdateTime:0 Value:1.2 ValueS: ValueB:false ValueD: Sum:0} {BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:-4 UpdateTime:0 Value:1.3 ValueS: ValueB:false ValueD: Sum:0} {BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:-3 UpdateTime:0 Value:1.4 ValueS: ValueB:false ValueD: Sum:0} {BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:-2 UpdateTime:0 Value:1.5 ValueS: ValueB:false ValueD: Sum:0} {BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:-1 UpdateTime:0 Value:1.6 ValueS: ValueB:false ValueD: Sum:0} {BaseName: BaseTime:0 BaseUnit: BaseValue:0 BaseSum:0 BaseVersion:0 Name:current Unit: Time:0 UpdateTime:0 Value:1.7 ValueS: ValueB:false ValueD: Sum:0}
// Use "keyasint" struct tag option to encode/decode struct to/from CBOR map. // Partial COSE header definition type coseHeader struct { Alg int `cbor:"1,keyasint,omitempty"` Kid []byte `cbor:"4,keyasint,omitempty"` IV []byte `cbor:"5,keyasint,omitempty"` } // Use "toarray" struct tag option to encode/decode struct to/from CBOR array. type signedCWT struct { _ struct{} `cbor:",toarray"` Protected []byte Unprotected coseHeader Payload []byte Signature []byte } // Data from https://tools.ietf.org/html/rfc8392#appendix-A section A.3 data, _ := hex.DecodeString("d28443a10126a104524173796d6d657472696345434453413235365850a70175636f61703a2f2f61732e6578616d706c652e636f6d02656572696b77037818636f61703a2f2f6c696768742e6578616d706c652e636f6d041a5612aeb0051a5610d9f0061a5610d9f007420b7158405427c1ff28d23fbad1f29c4c7c6a555e601d6fa29f9179bc3d7438bacaca5acd08c8d4d4f96131680c429a01f85951ecee743a52b9b63632c57209120e1c9e30") var v signedCWT if err := cbor.Unmarshal(data, &v); err != nil { fmt.Println("error:", err) } if _, err := cbor.Marshal(v); err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", v)
Output: {_:{} Protected:[161 1 38] Unprotected:{Alg:0 Kid:[65 115 121 109 109 101 116 114 105 99 69 67 68 83 65 50 53 54] IV:[]} Payload:[167 1 117 99 111 97 112 58 47 47 97 115 46 101 120 97 109 112 108 101 46 99 111 109 2 101 101 114 105 107 119 3 120 24 99 111 97 112 58 47 47 108 105 103 104 116 46 101 120 97 109 112 108 101 46 99 111 109 4 26 86 18 174 176 5 26 86 16 217 240 6 26 86 16 217 240 7 66 11 113] Signature:[84 39 193 255 40 210 63 186 209 242 156 76 124 106 85 94 96 29 111 162 159 145 121 188 61 116 56 186 202 202 90 205 8 200 212 212 249 97 49 104 12 66 154 1 248 89 81 236 238 116 58 82 185 182 54 50 197 114 9 18 14 28 158 48]}
// Use "keyasint" struct tag option to encode/decode struct to/from CBOR map. // Partial COSE header definition type coseHeader struct { Alg int `cbor:"1,keyasint,omitempty"` Kid []byte `cbor:"4,keyasint,omitempty"` IV []byte `cbor:"5,keyasint,omitempty"` } // Use "toarray" struct tag option to encode/decode struct to/from CBOR array. type signedCWT struct { _ struct{} `cbor:",toarray"` Protected []byte Unprotected coseHeader Payload []byte Signature []byte } // Data from https://tools.ietf.org/html/rfc8392#appendix-A section A.3 data, _ := hex.DecodeString("d28443a10126a104524173796d6d657472696345434453413235365850a70175636f61703a2f2f61732e6578616d706c652e636f6d02656572696b77037818636f61703a2f2f6c696768742e6578616d706c652e636f6d041a5612aeb0051a5610d9f0061a5610d9f007420b7158405427c1ff28d23fbad1f29c4c7c6a555e601d6fa29f9179bc3d7438bacaca5acd08c8d4d4f96131680c429a01f85951ecee743a52b9b63632c57209120e1c9e30") // Register tag COSE_Sign1 18 with signedCWT type. tags := cbor.NewTagSet() if err := tags.Add( cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired}, reflect.TypeOf(signedCWT{}), 18); err != nil { fmt.Println("error:", err) } dm, _ := cbor.DecOptions{}.DecModeWithTags(tags) em, _ := cbor.EncOptions{}.EncModeWithTags(tags) var v signedCWT if err := dm.Unmarshal(data, &v); err != nil { fmt.Println("error:", err) } if _, err := em.Marshal(v); err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", v)
Output: {_:{} Protected:[161 1 38] Unprotected:{Alg:0 Kid:[65 115 121 109 109 101 116 114 105 99 69 67 68 83 65 50 53 54] IV:[]} Payload:[167 1 117 99 111 97 112 58 47 47 97 115 46 101 120 97 109 112 108 101 46 99 111 109 2 101 101 114 105 107 119 3 120 24 99 111 97 112 58 47 47 108 105 103 104 116 46 101 120 97 109 112 108 101 46 99 111 109 4 26 86 18 174 176 5 26 86 16 217 240 6 26 86 16 217 240 7 66 11 113] Signature:[84 39 193 255 40 210 63 186 209 242 156 76 124 106 85 94 96 29 111 162 159 145 121 188 61 116 56 186 202 202 90 205 8 200 212 212 249 97 49 104 12 66 154 1 248 89 81 236 238 116 58 82 185 182 54 50 197 114 9 18 14 28 158 48]}
// Use cbor.RawMessage to delay unmarshaling (AttStmt's data type depends on Fmt's value). type attestationObject struct { AuthnData []byte `cbor:"authData"` Fmt string `cbor:"fmt"` AttStmt cbor.RawMessage `cbor:"attStmt"` } data, _ := hex.DecodeString("a363666d74686669646f2d7532666761747453746d74a26373696758483046022100e7ab373cfbd99fcd55fd59b0f6f17fef5b77a20ddec3db7f7e4d55174e366236022100828336b4822125fb56541fb14a8a273876acd339395ec2dad95cf41c1dd2a9ae637835638159024e3082024a30820132a0030201020204124a72fe300d06092a864886f70d01010b0500302e312c302a0603550403132359756269636f2055324620526f6f742043412053657269616c203435373230303633313020170d3134303830313030303030305a180f32303530303930343030303030305a302c312a302806035504030c2159756269636f205532462045452053657269616c203234393431343937323135383059301306072a8648ce3d020106082a8648ce3d030107034200043d8b1bbd2fcbf6086e107471601468484153c1c6d3b4b68a5e855e6e40757ee22bcd8988bf3befd7cdf21cb0bf5d7a150d844afe98103c6c6607d9faae287c02a33b3039302206092b0601040182c40a020415312e332e362e312e342e312e34313438322e312e313013060b2b0601040182e51c020101040403020520300d06092a864886f70d01010b05000382010100a14f1eea0076f6b8476a10a2be72e60d0271bb465b2dfbfc7c1bd12d351989917032631d795d097fa30a26a325634e85721bc2d01a86303f6bc075e5997319e122148b0496eec8d1f4f94cf4110de626c289443d1f0f5bbb239ca13e81d1d5aa9df5af8e36126475bfc23af06283157252762ff68879bcf0ef578d55d67f951b4f32b63c8aea5b0f99c67d7d814a7ff5a6f52df83e894a3a5d9c8b82e7f8bc8daf4c80175ff8972fda79333ec465d806eacc948f1bab22045a95558a48c20226dac003d41fbc9e05ea28a6bb5e10a49de060a0a4f6a2676a34d68c4abe8c61874355b9027e828ca9e064b002d62e8d8cf0744921753d35e3c87c5d5779453e7768617574684461746158c449960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d976341000000000000000000000000000000000000000000408903fd7dfd2c9770e98cae0123b13a2c27828a106349bc6277140e7290b7e9eb7976aa3c04ed347027caf7da3a2fa76304751c02208acfc4e7fc6c7ebbc375c8a5010203262001215820ad7f7992c335b90d882b2802061b97a4fabca7e2ee3e7a51e728b8055e4eb9c7225820e0966ba7005987fece6f0e0e13447aa98cec248e4000a594b01b74c1cb1d40b3") var v attestationObject if err := cbor.Unmarshal(data, &v); err != nil { fmt.Println("error:", err) } if _, err := cbor.Marshal(v); err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", v)
This section is empty.
This section is empty.
Diagnose returns extended diagnostic notation (EDN) of the first CBOR data item using the DiagMode. Any remaining bytes are returned in rest.
Marshal returns the CBOR encoding of v using default encoding options. See EncOptions for encoding options.
Marshal uses the following encoding rules:
If value implements the Marshaler interface, Marshal calls its MarshalCBOR method.
If value implements encoding.BinaryMarshaler, Marhsal calls its MarshalBinary method and encode it as CBOR byte string.
Boolean values encode as CBOR booleans (type 7).
Positive integer values encode as CBOR positive integers (type 0).
Negative integer values encode as CBOR negative integers (type 1).
Floating point values encode as CBOR floating points (type 7).
String values encode as CBOR text strings (type 3).
[]byte values encode as CBOR byte strings (type 2).
Array and slice values encode as CBOR arrays (type 4).
Map values encode as CBOR maps (type 5).
Struct values encode as CBOR maps (type 5). Each exported struct field becomes a pair with field name encoded as CBOR text string (type 3) and field value encoded based on its type. See struct tag option "keyasint" to encode field name as CBOR integer (type 0 and 1). Also see struct tag option "toarray" for special field "_" to encode struct values as CBOR array (type 4).
Marshal supports format string stored under the "cbor" key in the struct field's tag. CBOR format string can specify the name of the field, "omitempty", "omitzero" and "keyasint" options, and special case "-" for field omission. If "cbor" key is absent, Marshal uses "json" key. When using the "json" key, the "omitzero" option is honored when building with Go 1.24+ to match stdlib encoding/json behavior.
Struct field name is treated as integer if it has "keyasint" option in its format string. The format string must specify an integer as its field name.
Special struct field "_" is used to specify struct level options, such as "toarray". "toarray" option enables Go struct to be encoded as CBOR array. "omitempty" and "omitzero" are disabled by "toarray" to ensure that the same number of elements are encoded every time.
Anonymous struct fields are marshaled as if their exported fields were fields in the outer struct. Marshal follows the same struct fields visibility rules used by JSON encoding package.
time.Time values encode as text strings specified in RFC3339 or numerical representation of seconds since January 1, 1970 UTC depending on EncOptions.Time setting. Also See EncOptions.TimeTag to encode time.Time as CBOR tag with tag number 0 or 1.
big.Int values encode as CBOR integers (type 0 and 1) if values fit. Otherwise, big.Int values encode as CBOR bignums (tag 2 and 3). See EncOptions.BigIntConvert to always encode big.Int values as CBOR bignums.
Pointer values encode as the value pointed to.
Interface values encode as the value stored in the interface.
Nil slice/map/pointer/interface values encode as CBOR nulls (type 7).
Values of other types cannot be encoded in CBOR. Attempting to encode such a value causes Marshal to return an UnsupportedTypeError.
type Animal struct { Age int Name string Owners []string Male bool } animal := Animal{Age: 4, Name: "Candy", Owners: []string{"Mary", "Joe"}} b, err := cbor.Marshal(animal) if err != nil { fmt.Println("error:", err) } fmt.Printf("%x\n", b)
Output: a46341676504644e616d656543616e6479664f776e65727382644d617279634a6f65644d616c65f4
This example uses Marshal to encode struct and map in canonical form.
type Animal struct { Age int Name string Contacts map[string]string Male bool } animal := Animal{Age: 4, Name: "Candy", Contacts: map[string]string{"Mary": "111-111-1111", "Joe": "222-222-2222"}} em, err := cbor.CanonicalEncOptions().EncMode() if err != nil { fmt.Println("error:", err) } b, err := em.Marshal(animal) if err != nil { fmt.Println("error:", err) } fmt.Printf("%x\n", b)
Output: a46341676504644d616c65f4644e616d656543616e647968436f6e7461637473a2634a6f656c3232322d3232322d32323232644d6172796c3131312d3131312d31313131
This example uses "keyasint" struct tag option to encode struct's field names as integer. This feature is very useful in handling COSE, CWT, SenML data.
type Record struct { Name string `cbor:"1,keyasint"` Unit string `cbor:"2,keyasint"` Measurement int `cbor:"3,keyasint"` } rec := Record{Name: "current", Unit: "V", Measurement: 1} b, err := cbor.Marshal(rec) if err != nil { fmt.Println("error:", err) } fmt.Printf("%x\n", b)
Output: a3016763757272656e740261560301
tm, _ := time.Parse(time.RFC3339, "2013-03-21T20:04:00Z") // Encode time as string in RFC3339 format with second precision. em, err := cbor.EncOptions{Time: cbor.TimeRFC3339}.EncMode() if err != nil { fmt.Println("error:", err) } b, err := em.Marshal(tm) if err != nil { fmt.Println("error:", err) } fmt.Printf("%x\n", b) // Encode time as numerical representation of seconds since January 1, 1970 UTC. em, err = cbor.EncOptions{Time: cbor.TimeUnix}.EncMode() if err != nil { fmt.Println("error:", err) } b, err = em.Marshal(tm) if err != nil { fmt.Println("error:", err) } fmt.Printf("%x\n", b)
Output: 74323031332d30332d32315432303a30343a30305a 1a514b67b0
This example uses "toarray" struct tag option to encode struct as CBOR array.
type Record struct { _ struct{} `cbor:",toarray"` Name string Unit string Measurement int } rec := Record{Name: "current", Unit: "V", Measurement: 1} b, err := cbor.Marshal(rec) if err != nil { fmt.Println("error:", err) } fmt.Printf("%x\n", b)
Output: 836763757272656e74615601
MarshalToBuffer encodes v into provided buffer (instead of using built-in buffer pool) and uses default encoding options.
NOTE: Unlike Marshal, the buffer provided to MarshalToBuffer can contain partially encoded data if error is returned.
See Marshal for more details.
Unmarshal parses the CBOR-encoded data into the value pointed to by v using default decoding options. If v is nil, not a pointer, or a nil pointer, Unmarshal returns an error.
To unmarshal CBOR into a value implementing the Unmarshaler interface, Unmarshal calls that value's UnmarshalCBOR method with a valid CBOR value.
To unmarshal CBOR byte string into a value implementing the encoding.BinaryUnmarshaler interface, Unmarshal calls that value's UnmarshalBinary method with decoded CBOR byte string.
To unmarshal CBOR into a pointer, Unmarshal sets the pointer to nil if CBOR data is null (0xf6) or undefined (0xf7). Otherwise, Unmarshal unmarshals CBOR into the value pointed to by the pointer. If the pointer is nil, Unmarshal creates a new value for it to point to.
To unmarshal CBOR into an empty interface value, Unmarshal uses the following rules:
CBOR booleans decode to bool. CBOR positive integers decode to uint64. CBOR negative integers decode to int64 (big.Int if value overflows). CBOR floating points decode to float64. CBOR byte strings decode to []byte. CBOR text strings decode to string. CBOR arrays decode to []interface{}. CBOR maps decode to map[interface{}]interface{}. CBOR null and undefined values decode to nil. CBOR times (tag 0 and 1) decode to time.Time. CBOR bignums (tag 2 and 3) decode to big.Int. CBOR tags with an unrecognized number decode to cbor.Tag
To unmarshal a CBOR array into a slice, Unmarshal allocates a new slice if the CBOR array is empty or slice capacity is less than CBOR array length. Otherwise Unmarshal overwrites existing elements, and sets slice length to CBOR array length.
To unmarshal a CBOR array into a Go array, Unmarshal decodes CBOR array elements into Go array elements. If the Go array is smaller than the CBOR array, the extra CBOR array elements are discarded. If the CBOR array is smaller than the Go array, the extra Go array elements are set to zero values.
To unmarshal a CBOR array into a struct, struct must have a special field "_" with struct tag `cbor:",toarray"`. Go array elements are decoded into struct fields. Any "omitempty" struct field tag option is ignored in this case.
To unmarshal a CBOR map into a map, Unmarshal allocates a new map only if the map is nil. Otherwise Unmarshal reuses the existing map and keeps existing entries. Unmarshal stores key-value pairs from the CBOR map into Go map. See DecOptions.DupMapKey to enable duplicate map key detection.
To unmarshal a CBOR map into a struct, Unmarshal matches CBOR map keys to the keys in the following priority:
Unmarshal tries an exact match for field name, then a case-insensitive match. Map key-value pairs without corresponding struct fields are ignored. See DecOptions.ExtraReturnErrors to return error at unknown field.
To unmarshal a CBOR text string into a time.Time value, Unmarshal parses text string formatted in RFC3339. To unmarshal a CBOR integer/float into a time.Time value, Unmarshal creates an unix time with integer/float as seconds and fractional seconds since January 1, 1970 UTC. As a special case, Infinite and NaN float values decode to time.Time's zero value.
To unmarshal CBOR null (0xf6) and undefined (0xf7) values into a slice/map/pointer, Unmarshal sets Go value to nil. Because null is often used to mean "not present", unmarshaling CBOR null and undefined value into any other Go type has no effect and returns no error.
Unmarshal supports CBOR tag 55799 (self-describe CBOR), tag 0 and 1 (time), and tag 2 and 3 (bignum).
Unmarshal returns ExtraneousDataError error (without decoding into v) if there are any remaining bytes following the first valid CBOR data item. See UnmarshalFirst, if you want to unmarshal only the first CBOR data item without ExtraneousDataError caused by remaining bytes.
type Animal struct { Age int Name string Owners []string Male bool } data, _ := hex.DecodeString("a46341676504644e616d656543616e6479664f776e65727382644d617279634a6f65644d616c65f4") var animal Animal err := cbor.Unmarshal(data, &animal) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", animal)
Output: {Age:4 Name:Candy Owners:[Mary Joe] Male:false}
cborRFC3339Time, _ := hex.DecodeString("74323031332d30332d32315432303a30343a30305a") tm := time.Time{} if err := cbor.Unmarshal(cborRFC3339Time, &tm); err != nil { fmt.Println("error:", err) } fmt.Printf("%+v\n", tm.UTC().Format(time.RFC3339Nano)) cborUnixTime, _ := hex.DecodeString("1a514b67b0") tm = time.Time{} if err := cbor.Unmarshal(cborUnixTime, &tm); err != nil { fmt.Println("error:", err) } fmt.Printf("%+v\n", tm.UTC().Format(time.RFC3339Nano))
Output: 2013-03-21T20:04:00Z 2013-03-21T20:04:00Z
UnmarshalFirst parses the first CBOR data item into the value pointed to by v using default decoding options. Any remaining bytes are returned in rest.
If v is nil, not a pointer, or a nil pointer, UnmarshalFirst returns an error.
See the documentation for Unmarshal for details.
Valid checks whether data is a well-formed encoded CBOR data item and that it complies with default restrictions such as MaxNestedLevels, MaxArrayElements, MaxMapPairs, etc.
If there are any remaining bytes after the CBOR data item, an ExtraneousDataError is returned.
WARNING: Valid doesn't check if encoded CBOR data item is valid (i.e. validity) and RFC 8949 distinctly defines what is "Valid" and what is "Well-formed".
Deprecated: Valid is kept for compatibility and should not be used. Use Wellformed instead because it has a more appropriate name.
Wellformed checks whether data is a well-formed encoded CBOR data item and that it complies with default restrictions such as MaxNestedLevels, MaxArrayElements, MaxMapPairs, etc.
If there are any remaining bytes after the CBOR data item, an ExtraneousDataError is returned.
WithRejectedSimpleValue registers the given simple value as rejected. If the simple value is encountered in a CBOR input during unmarshaling, an UnacceptableDataItemError is returned.
type BigIntConvertMode int
BigIntConvertMode specifies how to encode big.Int values.
BigIntDecMode specifies how to decode CBOR bignum to Go interface{}.
type BinaryMarshalerMode int
BinaryMarshalerMode specifies how to encode types that implement encoding.BinaryMarshaler.
type BinaryUnmarshalerMode int
BinaryUnmarshalerMode specifies how to decode into types that implement encoding.BinaryUnmarshaler.
ByteArrayMode specifies how to encode byte arrays.
type ByteSliceLaterFormatMode int
ByteSliceLaterFormatMode specifies which later format conversion hint (CBOR tag 21-23) to include (if any) when encoding Go byte slice to CBOR byte string. The encoder will always encode unmodified bytes from the byte slice and just wrap it within CBOR tag 21, 22, or 23 if specified. See "Expected Later Encoding for CBOR-to-JSON Converters" in RFC 8949 Section 3.4.5.2.
const ( ByteSliceLaterFormatNone ByteSliceLaterFormatMode = iota ByteSliceLaterFormatBase64URL ByteSliceLaterFormatBase64 ByteSliceLaterFormatBase16 )
ByteString represents CBOR byte string (major type 2). ByteString can be used when using a Go []byte is not possible or convenient. For example, Go doesn't allow []byte as map key, so ByteString can be used to support data formats having CBOR map with byte string keys. ByteString can also be used to encode invalid UTF-8 string as CBOR byte string. See DecOption.MapKeyByteStringMode for more details.
Bytes returns bytes representing ByteString.
MarshalCBOR encodes ByteString as CBOR byte string (major type 2).
UnmarshalCBOR decodes CBOR byte string (major type 2) to ByteString. Decoding CBOR null and CBOR undefined sets ByteString to be empty.
Deprecated: No longer used by this codec; kept for compatibility with user apps that directly call this function.
type ByteStringEncoding uint8
ByteStringEncoding specifies the base encoding that byte strings are notated.
const ( ByteStringBase16Encoding ByteStringEncoding = iota ByteStringBase32Encoding ByteStringBase32HexEncoding ByteStringBase64Encoding )
type ByteStringExpectedFormatError struct { }
ByteStringExpectedFormatError is returned when unmarshaling CBOR byte string fails when using non-default ByteStringExpectedFormat decoding option that makes decoder expect a specified format such as base64, hex, etc.
type ByteStringExpectedFormatMode int
ByteStringExpectedFormatMode specifies how to decode CBOR byte string into Go byte slice when the byte string is NOT enclosed in CBOR tag 21, 22, or 23. An error is returned if the CBOR byte string does not contain the expected format (e.g. base64) specified. For tags 21-23, see "Expected Later Encoding for CBOR-to-JSON Converters" in RFC 8949 Section 3.4.5.2.
type ByteStringToStringMode int
ByteStringToStringMode specifies the behavior when decoding a CBOR byte string into a Go string.
const ( ByteStringToStringForbidden ByteStringToStringMode = iota ByteStringToStringAllowed ByteStringToStringAllowedWithExpectedLaterEncoding )
type ByteStringToTimeMode int
ByteStringToTimeMode specifies the behavior when decoding a CBOR byte string into a Go time.Time.
DecMode is the main interface for CBOR decoding.
DecOptions specifies decoding options.
DecMode returns DecMode with immutable options and no tags (safe for concurrency).
DecModeWithSharedTags returns DecMode with immutable options and mutable shared tags (safe for concurrency).
DecModeWithTags returns DecMode with options and tags that are both immutable (safe for concurrency).
DecTagMode specifies how decoder handles tag number.
const ( DecTagIgnored DecTagMode = iota DecTagOptional DecTagRequired )
Decoder reads and decodes CBOR values from io.Reader.
type Animal struct { Age int Name string Owners []string Male bool } data, _ := hex.DecodeString("a46341676504644d616c65f4644e616d656543616e6479664f776e65727382644d617279634a6f65a46341676506644d616c65f5644e616d656452756479664f776e657273816543696e6479a46341676502644d616c65f5644e616d656444756b65664f776e65727381664e6f72746f6e") dec := cbor.NewDecoder(bytes.NewReader(data)) for { var animal Animal if err := dec.Decode(&animal); err != nil { if err != io.EOF { fmt.Println("error:", err) } break } fmt.Printf("%+v\n", animal) }
Output: {Age:4 Name:Candy Owners:[Mary Joe] Male:false} {Age:6 Name:Rudy Owners:[Cindy] Male:true} {Age:2 Name:Duke Owners:[Norton] Male:true}
NewDecoder returns a new decoder that reads and decodes from r using the default decoding options.
Buffered returns a reader for data remaining in Decoder's buffer. Returned reader is valid until the next call to Decode or Skip.
Decode reads CBOR value and decodes it into the value pointed to by v.
NumBytesRead returns the number of bytes read.
Skip skips to the next CBOR data item (if there is any), otherwise it returns error such as io.EOF, io.UnexpectedEOF, etc.
DiagMode is the main interface for CBOR diagnostic notation.
type DiagOptions struct { ByteStringEncoding ByteStringEncoding ByteStringHexWhitespace bool ByteStringText bool ByteStringEmbeddedCBOR bool CBORSequence bool FloatPrecisionIndicator bool MaxNestedLevels int MaxArrayElements int MaxMapPairs int }
DiagOptions specifies Diag options.
DiagMode returns a DiagMode with immutable options.
type DupMapKeyError struct { Key any Index int }
DupMapKeyError describes detected duplicate map key in CBOR map.
DupMapKeyMode specifies how to enforce duplicate map key. Two map keys are considered duplicates if:
EncMode is the main interface for CBOR encoding.
EncOptions specifies encoding options.
CTAP2EncOptions returns EncOptions for "CTAP2 Canonical CBOR" encoding, defined in CTAP specification, with the following rules:
CanonicalEncOptions returns EncOptions for "Canonical CBOR" encoding, defined in RFC 7049 Section 3.9 with the following rules:
CoreDetEncOptions returns EncOptions for "Core Deterministic" encoding, defined in RFC 7049bis with the following rules:
PreferredUnsortedEncOptions returns EncOptions for "Preferred Serialization" encoding, defined in RFC 7049bis with the following rules:
EncMode returns EncMode with immutable options and no tags (safe for concurrency).
EncModeWithSharedTags returns EncMode with immutable options and mutable shared tags (safe for concurrency).
EncModeWithTags returns EncMode with options and tags that are both immutable (safe for concurrency).
UserBufferEncMode returns UserBufferEncMode with immutable options and no tags (safe for concurrency).
UserBufferEncModeWithSharedTags returns UserBufferEncMode with immutable options and mutable shared tags (safe for concurrency).
UserBufferEncModeWithTags returns UserBufferEncMode with options and tags that are both immutable (safe for concurrency).
EncTagMode specifies how encoder handles tag number.
Encoder writes CBOR values to io.Writer.
type Animal struct { Age int Name string Owners []string Male bool } animals := []Animal{ {Age: 4, Name: "Candy", Owners: []string{"Mary", "Joe"}, Male: false}, {Age: 6, Name: "Rudy", Owners: []string{"Cindy"}, Male: true}, {Age: 2, Name: "Duke", Owners: []string{"Norton"}, Male: true}, } var buf bytes.Buffer em, err := cbor.CanonicalEncOptions().EncMode() if err != nil { fmt.Println("error:", err) } enc := em.NewEncoder(&buf) for _, animal := range animals { err := enc.Encode(animal) if err != nil { fmt.Println("error:", err) } } fmt.Printf("%x\n", buf.Bytes())
Output: a46341676504644d616c65f4644e616d656543616e6479664f776e65727382644d617279634a6f65a46341676506644d616c65f5644e616d656452756479664f776e657273816543696e6479a46341676502644d616c65f5644e616d656444756b65664f776e65727381664e6f72746f6e
ExampleEncoder_indefiniteLengthArray encodes a stream of elements as an indefinite length array. Encoder supports nested indefinite length values.
var buf bytes.Buffer enc := cbor.NewEncoder(&buf) // Start indefinite length array encoding. if err := enc.StartIndefiniteArray(); err != nil { fmt.Println("error:", err) } // Encode array element. if err := enc.Encode(1); err != nil { fmt.Println("error:", err) } // Encode array element. if err := enc.Encode([]int{2, 3}); err != nil { fmt.Println("error:", err) } // Start a nested indefinite length array as array element. if err := enc.StartIndefiniteArray(); err != nil { fmt.Println("error:", err) } // Encode nested array element. if err := enc.Encode(4); err != nil { fmt.Println("error:", err) } // Encode nested array element. if err := enc.Encode(5); err != nil { fmt.Println("error:", err) } // Close nested indefinite length array. if err := enc.EndIndefinite(); err != nil { fmt.Println("error:", err) } // Close outer indefinite length array. if err := enc.EndIndefinite(); err != nil { fmt.Println("error:", err) } fmt.Printf("%x\n", buf.Bytes())
Output: 9f018202039f0405ffff
ExampleEncoder_indefiniteLengthByteString encodes a stream of definite length byte string ("chunks") as an indefinite length byte string.
var buf bytes.Buffer encoder := cbor.NewEncoder(&buf) // Start indefinite length byte string encoding. if err := encoder.StartIndefiniteByteString(); err != nil { fmt.Println("error:", err) } // Encode definite length byte string. if err := encoder.Encode([]byte{1, 2}); err != nil { fmt.Println("error:", err) } // Encode definite length byte string. if err := encoder.Encode([3]byte{3, 4, 5}); err != nil { fmt.Println("error:", err) } // Close indefinite length byte string. if err := encoder.EndIndefinite(); err != nil { fmt.Println("error:", err) } fmt.Printf("%x\n", buf.Bytes())
Output: 5f42010243030405ff
ExampleEncoder_indefiniteLengthMap encodes a stream of elements as an indefinite length map. Encoder supports nested indefinite length values.
var buf bytes.Buffer em, err := cbor.EncOptions{Sort: cbor.SortCanonical}.EncMode() if err != nil { fmt.Println("error:", err) } enc := em.NewEncoder(&buf) // Start indefinite length map encoding. if err := enc.StartIndefiniteMap(); err != nil { fmt.Println("error:", err) } // Encode map key. if err := enc.Encode("a"); err != nil { fmt.Println("error:", err) } // Encode map value. if err := enc.Encode(1); err != nil { fmt.Println("error:", err) } // Encode map key. if err := enc.Encode("b"); err != nil { fmt.Println("error:", err) } // Start an indefinite length array as map value. if err := enc.StartIndefiniteArray(); err != nil { fmt.Println("error:", err) } // Encoded array element. if err := enc.Encode(2); err != nil { fmt.Println("error:", err) } // Encoded array element. if err := enc.Encode(3); err != nil { fmt.Println("error:", err) } // Close indefinite length array. if err := enc.EndIndefinite(); err != nil { fmt.Println("error:", err) } // Close indefinite length map. if err := enc.EndIndefinite(); err != nil { fmt.Println("error:", err) } fmt.Printf("%x\n", buf.Bytes())
Output: bf61610161629f0203ffff
ExampleEncoder_indefiniteLengthTextString encodes a stream of definite length text string ("chunks") as an indefinite length text string.
var buf bytes.Buffer encoder := cbor.NewEncoder(&buf) // Start indefinite length text string encoding. if err := encoder.StartIndefiniteTextString(); err != nil { fmt.Println("error:", err) } // Encode definite length text string. if err := encoder.Encode("strea"); err != nil { fmt.Println("error:", err) } // Encode definite length text string. if err := encoder.Encode("ming"); err != nil { fmt.Println("error:", err) } // Close indefinite length text string. if err := encoder.EndIndefinite(); err != nil { fmt.Println("error:", err) } fmt.Printf("%x\n", buf.Bytes())
Output: 7f657374726561646d696e67ff
NewEncoder returns a new encoder that writes to w using the default encoding options.
Encode writes the CBOR encoding of v.
EndIndefinite closes last opened indefinite length value.
StartIndefiniteArray starts array encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes elements of the array until EndIndefinite is called.
StartIndefiniteByteString starts byte string encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes definite length byte strings ("chunks") as one contiguous string until EndIndefinite is called.
StartIndefiniteMap starts array encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes elements of the map until EndIndefinite is called.
StartIndefiniteTextString starts text string encoding of indefinite length. Subsequent calls of (*Encoder).Encode() encodes definite length text strings ("chunks") as one contiguous string until EndIndefinite is called.
type ExtraDecErrorCond uint
ExtraDecErrorCond specifies extra conditions that should be treated as errors.
ExtraDecErrorNone indicates no extra error condition.
type ExtraneousDataError struct { }
ExtraneousDataError indicates found extraneous data following well-formed CBOR data item.
type FieldNameByteStringMode int
FieldNameByteStringMode specifies the behavior when decoding a CBOR byte string map key as a Go struct field name.
type FieldNameMatchingMode int
FieldNameMatchingMode specifies how string keys in CBOR maps are matched to Go struct field names.
FieldNameMode specifies the CBOR type to use when encoding struct field names.
type InadmissibleTagContentTypeError struct { }
InadmissibleTagContentTypeError is returned when unmarshaling built-in CBOR tags fails because of inadmissible type for tag content. Currently, the built-in CBOR tags in this codec are tags 0-3 and 21-23. See "Tag validity" in RFC 8949 Section 5.3.2.
IndefLengthMode specifies whether to allow indefinite length items.
type IndefiniteLengthError struct { }
IndefiniteLengthError indicates found disallowed indefinite length items.
InfConvertMode specifies how to encode Infinity and overrides ShortestFloatMode. ShortestFloatMode is not used for encoding Infinity and NaN values.
InfMode specifies how to decode floating-point values (major type 7, additional information 25 through 27) representing positive or negative infinity.
const ( InfDecodeAllowed InfMode = iota InfDecodeForbidden )
IntDecMode specifies which Go type (int64, uint64, or big.Int) should be used when decoding CBOR integers (major type 0 and 1) to Go interface{}.
const ( IntDecConvertNone IntDecMode = iota IntDecConvertSigned IntDecConvertSignedOrFail IntDecConvertSignedOrBigInt )
type InvalidMapKeyTypeError struct { GoType string }
InvalidMapKeyTypeError describes invalid Go map key type when decoding CBOR map. For example, Go doesn't allow slice as map key.
type InvalidUnmarshalError struct { }
InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
type MapKeyByteStringMode int
MapKeyByteStringMode specifies how to decode CBOR byte string (major type 2) as Go map key when decoding CBOR map key into an empty Go interface value. Specifically, this option applies when decoding CBOR map into - Go empty interface, or - Go map with empty interface as key type. The CBOR map key types handled by this option are - byte string - tagged byte string - nested tagged byte string
type Marshaler interface { MarshalCBOR() ([]byte, error) }
Marshaler is the interface implemented by types that can marshal themselves into valid CBOR.
type MarshalerError struct { }
MarshalerError represents error from checking encoded CBOR data item returned from MarshalCBOR for well-formedness and some very limited tag validation.
type MaxArrayElementsError struct { }
MaxArrayElementsError indicates exceeded max number of elements for CBOR arrays.
type MaxMapPairsError struct { }
MaxMapPairsError indicates exceeded max number of key-value pairs for CBOR maps.
type MaxNestedLevelError struct { }
MaxNestedLevelError indicates exceeded max nested level of any combination of CBOR arrays/maps/tags.
NaNConvertMode specifies how to encode NaN and overrides ShortestFloatMode. ShortestFloatMode is not used for encoding Infinity and NaN values.
const ( NaNConvert7e00 NaNConvertMode = iota NaNConvertNone NaNConvertPreserveSignal NaNConvertQuiet NaNConvertReject )
NaNMode specifies how to decode floating-point values (major type 7, additional information 25 through 27) representing NaN (not-a-number).
const ( NaNDecodeAllowed NaNMode = iota NaNDecodeForbidden )
type NilContainersMode int
NilContainersMode specifies how to encode nil slices and maps.
OmitEmptyMode specifies how to encode struct fields with omitempty tag. The default behavior omits if field value would encode as empty CBOR value.
RawMessage is a raw encoded CBOR value.
MarshalCBOR returns m or CBOR nil if m is nil.
UnmarshalCBOR creates a copy of data and saves to *m.
RawTag represents a tagged data item (CBOR major type 6), comprising a tag number and the raw tag content. The raw tag content (enclosed data item) is a CBOR-encoded data item. RawTag can be used to delay decoding a CBOR data item or precompute encoding a CBOR data item.
MarshalCBOR returns CBOR encoding of t.
UnmarshalCBOR sets *t with the tag number and the raw tag content copied from data.
Deprecated: No longer used by this codec; kept for compatibility with user apps that directly call this function.
type SemanticError struct { }
SemanticError is a description of a CBOR semantic error.
type ShortestFloatMode int
ShortestFloatMode specifies which floating-point format should be used as the shortest possible format for CBOR encoding. It is not used for encoding Infinity and NaN values.
SimpleValue represents CBOR simple value. CBOR simple value is:
CBOR simple values identified by 20..23 are: "false", "true" , "null", and "undefined". Other CBOR simple values are currently unassigned/reserved by IANA.
MarshalCBOR encodes SimpleValue as CBOR simple value (major type 7).
UnmarshalCBOR decodes CBOR simple value (major type 7) to SimpleValue.
Deprecated: No longer used by this codec; kept for compatibility with user apps that directly call this function.
type SimpleValueRegistry struct { }
SimpleValueRegistry is a registry of unmarshaling behaviors for each possible CBOR simple value number (0...23 and 32...255).
Creates a new SimpleValueRegistry. The registry state is initialized by executing the provided functions in order against a registry that is pre-populated with the defaults for all well-formed simple value numbers.
SortMode identifies supported sorting order.
StringMode specifies how to encode Go string values.
type SyntaxError struct { }
SyntaxError is a description of a CBOR syntax error.
type Tag struct { Number uint64 Content any }
Tag represents a tagged data item (CBOR major type 6), comprising a tag number and the unmarshaled tag content. NOTE: The same encoding and decoding options that apply to untagged CBOR data items also applies to tag content during encoding and decoding.
TagOptions specifies how encoder and decoder handle tag number.
TagSet is an interface to add and remove tag info. It is used by EncMode and DecMode to provide CBOR tag support.
NewTagSet returns TagSet (safe for concurrency).
type TagsMdError struct { }
TagsMdError indicates found disallowed CBOR tags.
TagsMode specifies whether to allow CBOR tags.
type TextMarshalerMode int
TextMarshalerMode specifies how to encode types that implement encoding.TextMarshaler.
type TextUnmarshalerMode int
TextUnmarshalerMode specifies how to decode into types that implement encoding.TextUnmarshaler.
TimeMode specifies how to encode time.Time values in compliance with RFC 8949 (CBOR): - Section 3.4.1: Standard Date/Time String - Section 3.4.2: Epoch-Based Date/Time For more info, see: - https://www.rfc-editor.org/rfc/rfc8949.html NOTE: User applications that prefer to encode time with fractional seconds to an integer (instead of floating point or text string) can use a CBOR tag number not assigned by IANA:
const ( TimeUnix TimeMode = iota TimeUnixMicro TimeUnixDynamic TimeRFC3339 TimeRFC3339Nano )
type TimeTagToAnyMode int
TimeTagToAnyMode specifies how to decode CBOR tag 0 and 1 into an empty interface (any). Based on the specified mode, Unmarshal can return a time.Time value or a time string in a specific format.
type TranscodeError struct { }
Transcoder is a scheme for transcoding a single CBOR encoded data item to or from a different data format.
enc, _ := cbor.EncOptions{ JSONMarshalerTranscoder: TranscoderFunc(func(w io.Writer, r io.Reader) error { d := json.NewDecoder(r) for { token, err := d.Token() if err == io.EOF { return nil } if err != nil { return err } switch token { case json.Delim('['): if _, err := w.Write([]byte{0x9f}); err != nil { return err } case json.Delim('{'): if _, err := w.Write([]byte{0xbf}); err != nil { return err } case json.Delim(']'), json.Delim('}'): if _, err := w.Write([]byte{0xff}); err != nil { return err } default: b, err := cbor.Marshal(token) if err != nil { return err } if _, err := w.Write(b); err != nil { return err } } } }), }.EncMode() got, _ := enc.Marshal(json.RawMessage(`{"a": [true, "z", {"y": 3.14}], "b": {"c": null}}`)) diag, _ := cbor.Diagnose(got) fmt.Println(diag)
Output: {_ "a": [_ true, "z", {_ "y": 3.14}], "b": {_ "c": null}}
var dec cbor.DecMode dec, _ = cbor.DecOptions{ DefaultMapType: reflect.TypeOf(map[string]any{}), JSONUnmarshalerTranscoder: TranscoderFunc(func(w io.Writer, r io.Reader) error { var tmp any if err := dec.NewDecoder(r).Decode(&tmp); err != nil { return err } return json.NewEncoder(w).Encode(tmp) }), }.DecMode() var got json.RawMessage if err := dec.Unmarshal(cbor.RawMessage{0xa2, 0x61, 'a', 0x01, 0x61, 'b', 0x83, 0xf4, 0xf5, 0xf6}, &got); err != nil { panic(err) } fmt.Println(string(got))
Output: {"a":1,"b":[false,true,null]}
UTF8Mode option specifies if decoder should decode CBOR Text containing invalid UTF-8 string.
const ( UTF8RejectInvalid UTF8Mode = iota UTF8DecodeInvalid )
type UnacceptableDataItemError struct { CBORType string Message string }
UnacceptableDataItemError is returned when unmarshaling a CBOR input that contains a data item that is not acceptable to a specific CBOR-based application protocol ("invalid or unexpected" as described in RFC 8949 Section 5 Paragraph 3).
type UnknownFieldError struct { Index int }
UnknownFieldError describes detected unknown field in CBOR map when decoding to Go struct.
UnmarshalTypeError describes a CBOR value that can't be decoded to a Go type.
type Unmarshaler interface { UnmarshalCBOR([]byte) error }
Unmarshaler is the interface implemented by types that wish to unmarshal CBOR data themselves. The input is a valid CBOR value. UnmarshalCBOR must copy the CBOR data if it needs to use it after returning.
type UnrecognizedTagToAnyMode int
UnrecognizedTagToAnyMode specifies how to decode unrecognized CBOR tag into an empty interface (any). Currently, recognized CBOR tag numbers are 0, 1, 2, 3, or registered by TagSet.
UnsupportedTypeError is returned by Marshal when attempting to encode value of an unsupported type.
type UnsupportedValueError struct { }
UnsupportedValueError is returned by Marshal when attempting to encode an unsupported value.
UserBufferEncMode is an interface for CBOR encoding, which extends EncMode by adding MarshalToBuffer to support user specified buffer rather than encoding into the built-in buffer pool.
WrongTagError describes mismatch between CBOR tag and registered tag.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4