msgpack.go 1.1 KB

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