controllers.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. if err := json.NewEncoder(w).Encode(j{"error": err.Error()}); err != nil {
  15. InternalErrorHandler(w, err)
  16. }
  17. }
  18. // BadRequestHandler will return an HTTP 500 as an HTTP response.
  19. func BadRequestHandler(w http.ResponseWriter, err error) {
  20. if err == nil {
  21. return
  22. }
  23. log.Debugln(err)
  24. w.WriteHeader(http.StatusBadRequest)
  25. if err := json.NewEncoder(w).Encode(j{"error": err.Error()}); err != nil {
  26. InternalErrorHandler(w, err)
  27. }
  28. }
  29. // WriteSimpleResponse will return a message as a response.
  30. func WriteSimpleResponse(w http.ResponseWriter, success bool, message string) {
  31. response := models.BaseAPIResponse{
  32. Success: success,
  33. Message: message,
  34. }
  35. w.Header().Set("Content-Type", "application/json")
  36. if success {
  37. w.WriteHeader(http.StatusOK)
  38. } else {
  39. w.WriteHeader(http.StatusBadRequest)
  40. }
  41. if err := json.NewEncoder(w).Encode(response); err != nil {
  42. InternalErrorHandler(w, err)
  43. }
  44. }
  45. // WriteResponse will return an object as a JSON encoded response.
  46. func WriteResponse(w http.ResponseWriter, response interface{}) {
  47. w.Header().Set("Content-Type", "application/json")
  48. w.WriteHeader(http.StatusOK)
  49. if err := json.NewEncoder(w).Encode(response); err != nil {
  50. InternalErrorHandler(w, err)
  51. }
  52. }
  53. // WriteString will return a basic string and a status code to the client.
  54. func WriteString(w http.ResponseWriter, text string, status int) error {
  55. w.Header().Set("Content-Type", "text/html")
  56. w.WriteHeader(status)
  57. _, err := w.Write([]byte(text))
  58. return err
  59. }