render.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Package render implements functionality related to response rendering.
  2. package render
  3. import (
  4. "encoding/json"
  5. "net/http"
  6. "google.golang.org/protobuf/encoding/protojson"
  7. "google.golang.org/protobuf/proto"
  8. "github.com/smallstep/certificates/api/log"
  9. )
  10. // JSON writes the passed value into the http.ResponseWriter.
  11. func JSON(w http.ResponseWriter, v interface{}) {
  12. JSONStatus(w, v, http.StatusOK)
  13. }
  14. // JSONStatus writes the given value into the http.ResponseWriter and the
  15. // given status is written as the status code of the response.
  16. func JSONStatus(w http.ResponseWriter, v interface{}, status int) {
  17. w.Header().Set("Content-Type", "application/json")
  18. w.WriteHeader(status)
  19. if err := json.NewEncoder(w).Encode(v); err != nil {
  20. log.Error(w, err)
  21. return
  22. }
  23. log.EnabledResponse(w, v)
  24. }
  25. // ProtoJSON writes the passed value into the http.ResponseWriter.
  26. func ProtoJSON(w http.ResponseWriter, m proto.Message) {
  27. ProtoJSONStatus(w, m, http.StatusOK)
  28. }
  29. // ProtoJSONStatus writes the given value into the http.ResponseWriter and the
  30. // given status is written as the status code of the response.
  31. func ProtoJSONStatus(w http.ResponseWriter, m proto.Message, status int) {
  32. w.Header().Set("Content-Type", "application/json")
  33. w.WriteHeader(status)
  34. b, err := protojson.Marshal(m)
  35. if err != nil {
  36. log.Error(w, err)
  37. return
  38. }
  39. if _, err := w.Write(b); err != nil {
  40. log.Error(w, err)
  41. return
  42. }
  43. // log.EnabledResponse(w, v)
  44. }