msgpack_entity.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. package restPack
  2. import (
  3. restful "github.com/emicklei/go-restful"
  4. "gopkg.in/vmihailenco/msgpack.v2"
  5. )
  6. const MIME_MSGPACK = "application/x-msgpack" // Accept or Content-Type used in Consumes() and/or Produces()
  7. // NewEntityAccessorMPack returns a new EntityReaderWriter for accessing MessagePack content.
  8. // This package is not initialized with such an accessor using the MIME_MSGPACK contentType.
  9. func NewEntityAccessorMsgPack() restful.EntityReaderWriter {
  10. return entityMsgPackAccess{}
  11. }
  12. // entityOctetAccess is a EntityReaderWriter for Octet encoding
  13. type entityMsgPackAccess struct {
  14. }
  15. // Read unmarshalls the value from byte slice and using msgpack to unmarshal
  16. func (e entityMsgPackAccess) Read(req *restful.Request, v interface{}) error {
  17. return msgpack.NewDecoder(req.Request.Body).Decode(v)
  18. }
  19. // Write marshals the value to byte slice and set the Content-Type Header.
  20. func (e entityMsgPackAccess) Write(resp *restful.Response, status int, v interface{}) error {
  21. if v == nil {
  22. resp.WriteHeader(status)
  23. // do not write a nil representation
  24. return nil
  25. }
  26. resp.WriteHeader(status)
  27. return msgpack.NewEncoder(resp).Encode(v)
  28. }