utils.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package api
  2. import (
  3. "encoding/json"
  4. "io"
  5. "log"
  6. "net/http"
  7. "github.com/smallstep/certificates/errs"
  8. "github.com/smallstep/certificates/logging"
  9. )
  10. // EnableLogger is an interface that enables response logging for an object.
  11. type EnableLogger interface {
  12. ToLog() (interface{}, error)
  13. }
  14. // LogError adds to the response writer the given error if it implements
  15. // logging.ResponseLogger. If it does not implement it, then writes the error
  16. // using the log package.
  17. func LogError(rw http.ResponseWriter, err error) {
  18. if rl, ok := rw.(logging.ResponseLogger); ok {
  19. rl.WithFields(map[string]interface{}{
  20. "error": err,
  21. })
  22. } else {
  23. log.Println(err)
  24. }
  25. }
  26. // LogEnabledResponse log the response object if it implements the EnableLogger
  27. // interface.
  28. func LogEnabledResponse(rw http.ResponseWriter, v interface{}) {
  29. if el, ok := v.(EnableLogger); ok {
  30. out, err := el.ToLog()
  31. if err != nil {
  32. LogError(rw, err)
  33. return
  34. }
  35. if rl, ok := rw.(logging.ResponseLogger); ok {
  36. rl.WithFields(map[string]interface{}{
  37. "response": out,
  38. })
  39. } else {
  40. log.Println(out)
  41. }
  42. }
  43. }
  44. // JSON writes the passed value into the http.ResponseWriter.
  45. func JSON(w http.ResponseWriter, v interface{}) {
  46. JSONStatus(w, v, http.StatusOK)
  47. }
  48. // JSON writes the passed value into the http.ResponseWriter.
  49. func WriteProcessing(w http.ResponseWriter, v interface{}) {
  50. JSONStatus(w, v, http.StatusProcessing)
  51. }
  52. // JSONStatus writes the given value into the http.ResponseWriter and the
  53. // given status is written as the status code of the response.
  54. func JSONStatus(w http.ResponseWriter, v interface{}, status int) {
  55. w.Header().Set("Content-Type", "application/json")
  56. w.WriteHeader(status)
  57. if err := json.NewEncoder(w).Encode(v); err != nil {
  58. LogError(w, err)
  59. return
  60. }
  61. LogEnabledResponse(w, v)
  62. }
  63. // ReadJSON reads JSON from the request body and stores it in the value
  64. // pointed by v.
  65. func ReadJSON(r io.Reader, v interface{}) error {
  66. if err := json.NewDecoder(r).Decode(v); err != nil {
  67. return errs.Wrap(http.StatusBadRequest, err, "error decoding json")
  68. }
  69. return nil
  70. }