-
it looks like I have to define a new type in order to map cbor tag to "string" type NewString string
func (r *NewString) Unmarshal(...) {
...
} is there a way to map cbor tag directly to golang basic type string without defining a new type? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Hi @agufagit,
We intentionally don't provide a direct mapping between CBOR tags and Go's basic types. We need to define new Go types to map to CBOR tags. This approach prevents mistakes and other issues because a Go BTW, if you just need out-of-box support for // Example for disussion and issue at:
// - https://github.com/fxamacker/cbor/discussions/599
// - https://github.com/surrealdb/surrealdb.go/issues/169
package main
import (
"fmt"
"reflect"
"github.com/fxamacker/cbor/v2"
)
type myString string
func main() {
// Associate myString type with CBOR tag 100
tagNum := uint64(100)
myStringType := reflect.TypeOf(myString(""))
tags := cbor.NewTagSet()
err := tags.Add(cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired}, myStringType, tagNum)
if err != nil {
panic(fmt.Sprintf("TagSet.Add(%s, %d) returned error %v", myStringType, tagNum, err))
}
// Encode value of myString type
em, _ := cbor.EncOptions{}.EncModeWithTags(tags)
b, err := em.Marshal(myString("hello"))
if err != nil {
fmt.Printf("Marshal() returned error %v\n", err)
return
}
edn, _ := cbor.Diagnose(b) // human-readable representation (used for discussing binary data)
fmt.Printf("myString(\"hello\") is encoded to %x (EDN: %s)\n", b, edn)
// Decode CBOR data item to v interface{} which is
// automatically detected and decoded as a myString value.
dm, _ := cbor.DecOptions{}.DecModeWithTags(tags)
var v interface{}
err = dm.Unmarshal(b, &v)
if err != nil {
fmt.Printf("Unmarshal() returned error %v\n", err)
return
}
fmt.Printf("%x is decoded to \"%v\" (of type %T)\n", b, v, v)
// Output:
// myString("hello") is encoded to d8646568656c6c6f
// d8646568656c6c6f is decoded to "hello" (of type main.myString)
} |
Beta Was this translation helpful? Give feedback.
-
Hi @fxamacker, Thank you for the answer. I have one more question, for golang type this question is regarding this issue surrealdb/surrealdb.go#176 |
Beta Was this translation helpful? Give feedback.
-
Hi @agufagit,
Yes, it is automatic.
More info at https://github.com/fxamacker/cbor/blob/master/decode.go#L95-L98
|
Beta Was this translation helpful? Give feedback.
Hi @agufagit,
We intentionally don't provide a direct mapping between CBOR tags and Go's basic types. We need to define new Go types to map to CBOR tags.
This approach prevents mistakes and other issues because a Go
string
type can be used with different CBOR tags. For example, CBOR tags defined in RFC8949 1, 32, 33, 34, and 36 all use data item of CBOR text string type.BTW, if you just need out-of-box support for
NewString
with a CBOR tag, you don't need to implementNewString.Unmarshal
. For example, https://go.dev/play/p/CTcLik_KSB9