msgpack.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. //go:build !nomsgpack
  5. // +build !nomsgpack
  6. package render
  7. import (
  8. "net/http"
  9. "github.com/ugorji/go/codec"
  10. )
  11. var (
  12. _ Render = MsgPack{}
  13. )
  14. // MsgPack contains the given interface object.
  15. type MsgPack struct {
  16. Data interface{}
  17. }
  18. var msgpackContentType = []string{"application/msgpack; charset=utf-8"}
  19. // WriteContentType (MsgPack) writes MsgPack ContentType.
  20. func (r MsgPack) WriteContentType(w http.ResponseWriter) {
  21. writeContentType(w, msgpackContentType)
  22. }
  23. // Render (MsgPack) encodes the given interface object and writes data with custom ContentType.
  24. func (r MsgPack) Render(w http.ResponseWriter) error {
  25. return WriteMsgPack(w, r.Data)
  26. }
  27. // WriteMsgPack writes MsgPack ContentType and encodes the given interface object.
  28. func WriteMsgPack(w http.ResponseWriter, obj interface{}) error {
  29. writeContentType(w, msgpackContentType)
  30. var mh codec.MsgpackHandle
  31. return codec.NewEncoder(w, &mh).Encode(obj)
  32. }