protobuf.go 756 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package render
  2. import (
  3. "net/http"
  4. "github.com/gogo/protobuf/proto"
  5. "github.com/pkg/errors"
  6. )
  7. var pbContentType = []string{"application/x-protobuf"}
  8. // Render (PB) writes data with protobuf ContentType.
  9. func (r PB) Render(w http.ResponseWriter) error {
  10. if r.TTL <= 0 {
  11. r.TTL = 1
  12. }
  13. return writePB(w, r)
  14. }
  15. // WriteContentType write protobuf ContentType.
  16. func (r PB) WriteContentType(w http.ResponseWriter) {
  17. writeContentType(w, pbContentType)
  18. }
  19. func writePB(w http.ResponseWriter, obj PB) (err error) {
  20. var pbBytes []byte
  21. writeContentType(w, pbContentType)
  22. if pbBytes, err = proto.Marshal(&obj); err != nil {
  23. err = errors.WithStack(err)
  24. return
  25. }
  26. if _, err = w.Write(pbBytes); err != nil {
  27. err = errors.WithStack(err)
  28. }
  29. return
  30. }