controllers.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/owncast/owncast/models"
  6. "github.com/owncast/owncast/router/middleware"
  7. log "github.com/sirupsen/logrus"
  8. )
  9. type j map[string]interface{}
  10. // InternalErrorHandler will return an error message as an HTTP response.
  11. func InternalErrorHandler(w http.ResponseWriter, err error) {
  12. if err == nil {
  13. return
  14. }
  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 uncacheable response.
  47. func WriteResponse(w http.ResponseWriter, response interface{}) {
  48. w.Header().Set("Content-Type", "application/json")
  49. middleware.DisableCache(w)
  50. w.WriteHeader(http.StatusOK)
  51. if err := json.NewEncoder(w).Encode(response); err != nil {
  52. InternalErrorHandler(w, err)
  53. }
  54. }
  55. // WriteString will return a basic string and a status code to the client.
  56. func WriteString(w http.ResponseWriter, text string, status int) error {
  57. w.Header().Set("Content-Type", "text/html")
  58. w.WriteHeader(status)
  59. _, err := w.Write([]byte(text))
  60. return err
  61. }