httpResponse.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package utils
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. // JSONResponse convenient way to define jwtErrors
  7. type JSONResponse struct {
  8. Status string `json:"status"`
  9. Details string `json:"details"`
  10. }
  11. // TokenResponseStruct define JWT return format
  12. type TokenResponseStruct struct {
  13. Token string `json:"token"`
  14. Expiration int64 `json:"expiration"`
  15. }
  16. // JSONResponseToken convenient way to define jwtErrors
  17. type JSONResponseToken struct {
  18. Status string `json:"status"`
  19. Details TokenResponseStruct `json:"details"`
  20. }
  21. // SendJSONErrorResponse sends an API error encoding in JSON
  22. func SendJSONErrorResponse(w http.ResponseWriter, err string, status int) {
  23. var response = JSONResponse{
  24. Status: "error",
  25. Details: err,
  26. }
  27. js, error := json.Marshal(response)
  28. if error != nil {
  29. http.Error(w, error.Error(), http.StatusInternalServerError)
  30. return
  31. }
  32. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  33. w.WriteHeader(status)
  34. w.Write(js)
  35. }
  36. // SendJSONAcknowledgeResponse sends an API error encoding in JSON
  37. func SendJSONAcknowledgeResponse(w http.ResponseWriter, message string, status int) {
  38. var response = JSONResponse{
  39. Status: "ok",
  40. Details: message,
  41. }
  42. js, error := json.Marshal(response)
  43. if error != nil {
  44. http.Error(w, error.Error(), http.StatusInternalServerError)
  45. return
  46. }
  47. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  48. w.WriteHeader(status)
  49. w.Write(js)
  50. }
  51. // SendJSONTokenAcknowledgeResponse send token as JSON format
  52. func SendJSONTokenAcknowledgeResponse(w http.ResponseWriter, message TokenResponseStruct, status int) {
  53. var response = JSONResponseToken{
  54. Status: "ok",
  55. Details: message,
  56. }
  57. js, error := json.Marshal(response)
  58. if error != nil {
  59. http.Error(w, error.Error(), http.StatusInternalServerError)
  60. return
  61. }
  62. w.Header().Set("Content-Type", "application/json; charset=UTF-8")
  63. w.WriteHeader(status)
  64. w.Write(js)
  65. }