protobuf.go 861 B

123456789101112131415161718192021222324252627282930313233343536
  1. // Copyright 2018 Gin Core Team. 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 render
  5. import (
  6. "net/http"
  7. "github.com/golang/protobuf/proto"
  8. )
  9. // ProtoBuf contains the given interface object.
  10. type ProtoBuf struct {
  11. Data interface{}
  12. }
  13. var protobufContentType = []string{"application/x-protobuf"}
  14. // Render (ProtoBuf) marshals the given interface object and writes data with custom ContentType.
  15. func (r ProtoBuf) Render(w http.ResponseWriter) error {
  16. r.WriteContentType(w)
  17. bytes, err := proto.Marshal(r.Data.(proto.Message))
  18. if err != nil {
  19. return err
  20. }
  21. _, err = w.Write(bytes)
  22. return err
  23. }
  24. // WriteContentType (ProtoBuf) writes ProtoBuf ContentType.
  25. func (r ProtoBuf) WriteContentType(w http.ResponseWriter) {
  26. writeContentType(w, protobufContentType)
  27. }