You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.6 KiB

8 months ago
3 years ago
  1. package middleware
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "net/http"
  6. "git.hoogi.eu/snafu/go-blog/logger"
  7. "git.hoogi.eu/snafu/go-blog/models"
  8. )
  9. // XMLHandler marshals XML and writes to the http response
  10. type XMLHandler struct {
  11. AppCtx *AppContext
  12. Handler XHandler
  13. }
  14. // XHandler enriches handler with the AppContext
  15. type XHandler func(*AppContext, http.ResponseWriter, *http.Request) (*models.XMLData, error)
  16. func (fn XMLHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  17. rw.Header().Set("Content-Type", "application/xml")
  18. h, err := fn.Handler(fn.AppCtx, rw, r)
  19. if err != nil {
  20. logger.Log.Error(err)
  21. x, err := xml.Marshal(err)
  22. if err != nil {
  23. logger.Log.Error(err)
  24. http.Error(rw, err.Error(), http.StatusInternalServerError)
  25. return
  26. }
  27. if _, err = rw.Write(x); err != nil {
  28. logger.Log.Error(err)
  29. http.Error(rw, err.Error(), http.StatusInternalServerError)
  30. return
  31. }
  32. return
  33. }
  34. x, err2 := xml.MarshalIndent(h.Data, "", "\t")
  35. if err2 != nil {
  36. http.Error(rw, err2.Error(), http.StatusInternalServerError)
  37. return
  38. }
  39. x = []byte(xml.Header + string(x))
  40. if h.HexEncode {
  41. x = bytes.Replace(x, []byte("&"), []byte("&"), -1) // &
  42. x = bytes.Replace(x, []byte("'"), []byte("'"), -1) // '
  43. x = bytes.Replace(x, []byte("""), []byte("""), -1) // "
  44. x = bytes.Replace(x, []byte("&lt;"), []byte("&#x3c;"), -1) // <
  45. x = bytes.Replace(x, []byte("&gt;"), []byte("&#x3e;"), -1) // >
  46. }
  47. if _, err := rw.Write(x); err != nil {
  48. logger.Log.Error(err)
  49. http.Error(rw, err.Error(), http.StatusInternalServerError)
  50. return
  51. }
  52. }