controllers.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/owncast/owncast/models"
  6. log "github.com/sirupsen/logrus"
  7. )
  8. type j map[string]interface{}
  9. // InternalErrorHandler will return an error message as an HTTP response.
  10. func InternalErrorHandler(w http.ResponseWriter, err error) {
  11. if err == nil {
  12. return
  13. }
  14. w.WriteHeader(http.StatusInternalServerError)
  15. if err := json.NewEncoder(w).Encode(j{"error": err.Error()}); err != nil {
  16. InternalErrorHandler(w, err)
  17. }
  18. }
  19. // BadRequestHandler will return an HTTP 500 as an HTTP response.
  20. func BadRequestHandler(w http.ResponseWriter, err error) {
  21. if err == nil {
  22. return
  23. }
  24. log.Debugln(err)
  25. w.WriteHeader(http.StatusBadRequest)
  26. if err := json.NewEncoder(w).Encode(j{"error": err.Error()}); err != nil {
  27. InternalErrorHandler(w, err)
  28. }
  29. }
  30. // WriteSimpleResponse will return a message as a response.
  31. func WriteSimpleResponse(w http.ResponseWriter, success bool, message string) {
  32. response := models.BaseAPIResponse{
  33. Success: success,
  34. Message: message,
  35. }
  36. w.Header().Set("Content-Type", "application/json")
  37. if success {
  38. w.WriteHeader(http.StatusOK)
  39. } else {
  40. w.WriteHeader(http.StatusBadRequest)
  41. }
  42. if err := json.NewEncoder(w).Encode(response); err != nil {
  43. InternalErrorHandler(w, err)
  44. }
  45. }
  46. // WriteResponse will return an object as a JSON encoded response.
  47. func WriteResponse(w http.ResponseWriter, response interface{}) {
  48. w.Header().Set("Content-Type", "application/json")
  49. w.WriteHeader(http.StatusOK)
  50. if err := json.NewEncoder(w).Encode(response); err != nil {
  51. InternalErrorHandler(w, err)
  52. }
  53. }