It's cloned from viant/gohessian , and do the following works:
- fix lots of bugs
- large scope refactoring to let code structure simple and human-friendly
- add ref and date features implement
- more unit tests
- api refactoring
name map
: amap[string]string
used byencoder
to determine the class name of a objecttype map
: amap[string]reflect.Type
used bydecoder
to determine the type of instance to initialize
You can use function hessian.ExtractTypeNameMap(interface{})
to generate both the type map and name map.
It's the recommendation way.
Of course, you can create by yourself, but make sure them contain all names and types which encoder and decoder needed.
type circular struct {
Num int
Previous *circular
Next *circular
}
func main() {
c := &circular{}
c.Num = 12345
c.Previous = c
c.Next = c
// create hessian serializer
serializer := hessian.NewSerializer(hessian.ExtractTypeNameMap(c))
fmt.Println("source object: ", c)
// encode to bytes
bytes, err := serializer.Encode(c)
if err != nil {
panic(err)
}
// decode from bytes
decoded, err := serializer.Decode(bytes)
if err != nil {
panic(err)
}
fmt.Println("decode object: ", decoded)
}
You can define a function HessianCodecName() string
for your struct if using hessian.ExtractTypeNameMap(interface{})
to generate type map and name map.
type TraceVo struct {
Key string
Value string
}
func (TraceVo) HessianCodecName() string {
return "hessian.TraceVo"
}
typeMap,nameMap := hessian.ExtractTypeNameMap(&TraceVo{})
If you create type map and name map manually, you should also add the java class name mapping.
hessian.NewSerializer
contains serialization processing data, so a serializer can't be used concurrently, you should create a new one when needed.
If there is only one type of data to serialize , a goroutine can continue use the same serializer to Encode()
or Decode()
.
The following is a client-server streaming transport example:
server side:
_,nameMap := hessian.ExtractTypeNameMap(object)
encoder := hessian.NewEncoder(outputStreamWriter, nameMap) // write stream to outputStreamWriter
for {
data := getNewData()
err = encoder.Write(data) // write new data
if err != nil {
panic(err)
}
}
client side:
typeMap,_ := hessian.ExtractTypeNameMap(object)
decoder := hessian.NewDecoder(inputStreamReader, typeMap) // read stream from inputStreamReader
for {
obj,err := decoder.Read() // read new object
if err != nil {
panic(err)
}
// process obj
}