rsocket / rsocket-go

rsocket-go implementation
Apache License 2.0
511 stars 44 forks source link

Support Json encoding/decoding #2

Closed szihai closed 5 years ago

szihai commented 5 years ago

Json is a popular encoding mechanism. The sdk should support Json format payload.

fiorix commented 5 years ago

Same comment I left in #3: why?

jjeffcaii commented 5 years ago

Implement interface payload.Payload. Here're some examples:

package example

import (
    "encoding/json"

    "github.com/rsocket/rsocket-go/payload"
)

type JSONPayload struct {
    d interface{}
    m []byte
}

func (p *JSONPayload) Metadata() (metadata []byte, ok bool) {
    if len(p.m) < 1 {
        return
    }
    return p.m, true
}

func (p *JSONPayload) MetadataUTF8() (metadata string, ok bool) {
    if len(p.m) < 1 {
        return
    }
    return string(p.m), true
}

func (p *JSONPayload) Data() []byte {
    bs, err := json.Marshal(p.d)
    if err != nil {
        panic(err)
    }
    return bs
}

func (p *JSONPayload) DataUTF8() string {
    bs, err := json.Marshal(p.d)
    if err != nil {
        panic(err)
    }
    return string(bs)
}

func (p *JSONPayload) Release() {
    // ignore
}

func NewJSONPayload(data interface{}, metadata []byte) payload.Payload {
    return &JSONPayload{
        d: data,
        m: metadata,
    }
}