mtest/mtest.go
Vincent Batts 80fe32f52e
just looking at outputs of CBOR for comparison
pulled the serving-crds.yaml for knative, then made a json form of it,
for marshaling to cbor for comparison

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
2020-12-03 11:43:21 -05:00

104 lines
2.4 KiB
Go

package mtest
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/fxamacker/cbor/v2"
"github.com/sirupsen/logrus"
)
type Sample struct {
User struct {
Name string `json:"n",cbor:"n"`
Email string `json:"e",cbor:"e"`
} `json:"n",cbor:"n"`
Annotations map[string]string `json:"a",cbor:"a"`
}
func OtherThings() {
opts := cbor.CanonicalEncOptions()
// If needed, modify opts. For example: opts.Time = cbor.TimeUnix
// Create reusable EncMode interface with immutable options, safe for concurrent use.
em, err := opts.EncMode()
if err != nil {
logrus.Fatal(err)
}
jbuf, err := ioutil.ReadFile("serving-crds.json")
if err != nil {
logrus.Fatal(err)
}
d := []map[string]interface{}{}
err = json.Unmarshal(jbuf, &d)
if err != nil {
logrus.Fatal(err)
}
logrus.Info("writing to serving-crds.cbor")
fd, err := os.OpenFile("serving-crds.cbor", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0644))
if err != nil {
logrus.Fatal(err)
}
defer fd.Close()
encoder := em.NewEncoder(fd) // create encoder with io.Writer w
err = encoder.Encode(d) // encode v to io.Writer w
if err != nil {
logrus.Fatal(err)
}
}
func Things() {
opts := cbor.CanonicalEncOptions()
// If needed, modify opts. For example: opts.Time = cbor.TimeUnix
// Create reusable EncMode interface with immutable options, safe for concurrent use.
em, err := opts.EncMode()
if err != nil {
logrus.Fatal(err)
}
s := Sample{}
s.User.Name = "Vincent Batts"
s.User.Email = "vbatts@hashbangbash.com"
s.Annotations = map[string]string{
"farts": "a lot",
}
// Use EncMode like encoding/json, with same function signatures.
b, err := em.Marshal(s) // encode v to []byte b
if err != nil {
logrus.Fatal(err)
}
_ = b
logrus.Info("writing to output.cbor")
fd1, err := os.OpenFile("output.cbor", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0644))
if err != nil {
logrus.Fatal(err)
}
defer fd1.Close()
encoder := em.NewEncoder(fd1) // create encoder with io.Writer w
err = encoder.Encode(s) // encode v to io.Writer w
if err != nil {
logrus.Fatal(err)
}
logrus.Info("writing to output.json")
fd2, err := os.OpenFile("output.json", os.O_CREATE|os.O_WRONLY, os.FileMode(0644))
if err != nil {
logrus.Fatal(err)
}
defer fd2.Close()
jenc := json.NewEncoder(fd2) // create encoder with io.Writer w
err = jenc.Encode(s) // encode v to io.Writer w
if err != nil {
logrus.Fatal(err)
}
}