ugorji / go

idiomatic codec and rpc lib for msgpack, cbor, json, etc. msgpack.org[Go]
MIT License
1.86k stars 295 forks source link

Encode does not encode []uint8 inside struct #74

Closed pctj101 closed 9 years ago

pctj101 commented 9 years ago

I'm including a program below which shows how the key "options" and the associated []uint8 does not get encoded into Msgpack output.

If I change the encoding to JSON I get {} (basically empty)

Is there an extension I'm missing?

package main

import (
    "log"
    "fmt"
    "bytes"
    "bufio"
    "reflect"
    "github.com/ugorji/go/codec"
)

type MyStruct struct {
    _struct bool    `codec:",omitempty"`   //set omitempty for every field
    Field1 string   `codec:"x"`            //skip this field
    Field2 uint8      `codec:"yourName"`       //Use key "myName" in encode stream
    Field3 int32    `codec:",omitempty"`   //use key "Field3". Omit if empty.
    Field4 bool     `codec:"f4,omitempty"` //use key "f4". Omit if empty.
    options []uint8    `codec:"options"`
}

func main() {
    w := new(bytes.Buffer)
    h := new(codec.MsgpackHandle)
    h.MapType = reflect.TypeOf(map[string]interface{}(nil))
    wb := bufio.NewWriter(w)
    intarr := []uint8{0, 1, 2, 3}
    // data := MyStruct{Field1: "hihi", Field2: 1, Field3: 4, Field4: true, options: intarr}
    data := MyStruct{options: intarr}

    fmt.Println(data)

    enc := codec.NewEncoder(wb, h)
    if err := enc.Encode(data); err != nil  {
        fmt.Println("Oops")
        fmt.Println(err)
    } else {
        wb.Flush()
        log.Printf("-> %s [%d bytes]", w.Bytes(), w.Len())
    }

}
pctj101 commented 9 years ago

other silly people like me may consider using an upper case 'O' for options to make the field publicly accessible