render.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package render
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "html/template"
  6. "net/http"
  7. "github.com/vladimirok5959/golang-utils/utils/http/helpers"
  8. "github.com/vladimirok5959/golang-utils/utils/http/logger"
  9. )
  10. // func HTML(w http.ResponseWriter, r *http.Request, f template.FuncMap, d interface{}, s string, httpStatusCode int) bool
  11. // func JSON(w http.ResponseWriter, r *http.Request, o interface{}) bool
  12. func HTML(w http.ResponseWriter, r *http.Request, f template.FuncMap, d interface{}, s string, httpStatusCode int) bool {
  13. tmpl := template.New("tmpl")
  14. if f != nil {
  15. tmpl = tmpl.Funcs(f)
  16. }
  17. var err error
  18. tmpl, err = tmpl.Parse(s)
  19. if err != nil {
  20. helpers.RespondAsBadRequest(w, r, err)
  21. return false
  22. }
  23. type Response struct {
  24. Data interface{}
  25. }
  26. var html bytes.Buffer
  27. if err := tmpl.Execute(&html, Response{Data: d}); err != nil {
  28. helpers.RespondAsBadRequest(w, r, err)
  29. return false
  30. }
  31. w.Header().Set("Content-Type", "text/html")
  32. w.WriteHeader(httpStatusCode)
  33. if _, err := w.Write([]byte(helpers.MinifyHtmlCode(html.String()))); err != nil {
  34. logger.LogInternalError(err)
  35. }
  36. return true
  37. }
  38. func JSON(w http.ResponseWriter, r *http.Request, o interface{}) bool {
  39. j, err := json.Marshal(o)
  40. if err != nil {
  41. helpers.RespondAsBadRequest(w, r, err)
  42. return false
  43. }
  44. w.Header().Set("Content-Type", "application/json")
  45. if _, err := w.Write(j); err != nil {
  46. logger.LogInternalError(err)
  47. }
  48. return true
  49. }