utils.go 1.3 KB

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