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