msgpack.go 1.2 KB

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