Hi,

I've been informed of how exactly to use the CBOR tag solution by the 
author of one of the cbor.io recommended CBOR libraries:

https://github.com/fxamacker/cbor/issues/241#issuecomment-656881180

This solution is clearly a bit nicer than the wrapping struct solution but 
it's specific to the given CBOR library whereas the wrapping struct 
solution would likely work with any serialization library.
Not that Brian and Jonathan both suggested this solution... however it's 
very helpful to see this code example of how exactly to do it since it 
wasn't immediately obvious from reading the API docs of the various CBOR 
libraries.
I shall quote the author's code sample herein:
"""

// Create TagSet with tag number and Go type
tags := cbor.NewTagSet()
err := tags.Add(
    cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired},
    reflect.TypeOf(MyType{}),    // your custom type
    MyTypeCBORTagNumber,         // CBOR tag number for your custom type
)

// Create decoding mode with TagSet     
dm, err := cbor.DecOptions{}.DecModeWithTags(tags)

// Decode unknown CBOR blob
var v interface{}
err = dm.Unmarshal(b, &v) 
  
// Use type switch to handle different types
switch v := v.(type) {
case MyType:  // custom type
    ...
default:
    ...
}


"""

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/8ffa761a-bfec-4658-bccd-f9a5b1297991o%40googlegroups.com.

Reply via email to