4
0

utils.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package api
  2. import (
  3. "encoding/json"
  4. "io"
  5. "log"
  6. "net/http"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/certificates/logging"
  9. )
  10. // LogError adds to the response writer the given error if it implements
  11. // logging.ResponseLogger. If it does not implement it, then writes the error
  12. // using the log package.
  13. func LogError(rw http.ResponseWriter, err error) {
  14. if rl, ok := rw.(logging.ResponseLogger); ok {
  15. rl.WithFields(map[string]interface{}{
  16. "error": err,
  17. })
  18. } else {
  19. log.Println(err)
  20. }
  21. }
  22. // JSON writes the passed value into the http.ResponseWriter.
  23. func JSON(w http.ResponseWriter, v interface{}) {
  24. w.Header().Set("Content-Type", "application/json")
  25. if err := json.NewEncoder(w).Encode(v); err != nil {
  26. LogError(w, err)
  27. }
  28. }
  29. // ReadJSON reads JSON from the request body and stores it in the value
  30. // pointed by v.
  31. func ReadJSON(r io.Reader, v interface{}) error {
  32. if err := json.NewDecoder(r).Decode(v); err != nil {
  33. return BadRequest(errors.Wrap(err, "error decoding json"))
  34. }
  35. return nil
  36. }