msgpack.go 770 B

1234567891011121314151617181920212223242526272829303132333435
  1. // Copyright 2017 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package binding
  5. import (
  6. "bytes"
  7. "io"
  8. "net/http"
  9. "github.com/ugorji/go/codec"
  10. )
  11. type msgpackBinding struct{}
  12. func (msgpackBinding) Name() string {
  13. return "msgpack"
  14. }
  15. func (msgpackBinding) Bind(req *http.Request, obj interface{}) error {
  16. return decodeMsgPack(req.Body, obj)
  17. }
  18. func (msgpackBinding) BindBody(body []byte, obj interface{}) error {
  19. return decodeMsgPack(bytes.NewReader(body), obj)
  20. }
  21. func decodeMsgPack(r io.Reader, obj interface{}) error {
  22. cdc := new(codec.MsgpackHandle)
  23. if err := codec.NewDecoder(r, cdc).Decode(&obj); err != nil {
  24. return err
  25. }
  26. return validate(obj)
  27. }