error.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package main
  2. /*
  3. This page mainly used to handle error interfaces
  4. */
  5. import (
  6. "io/ioutil"
  7. "net/http"
  8. "strings"
  9. fs "imuslab.com/arozos/mod/filesystem"
  10. )
  11. func errorHandleNotFound(w http.ResponseWriter, r *http.Request) {
  12. notFoundPage := "./web/SystemAO/notfound.html"
  13. if fs.FileExists(notFoundPage) {
  14. notFoundTemplateBytes, err := ioutil.ReadFile(notFoundPage)
  15. notFoundTemplate := string(notFoundTemplateBytes)
  16. if err != nil {
  17. http.NotFound(w, r)
  18. } else {
  19. //Replace the request URL inside the page
  20. notFoundTemplate = strings.ReplaceAll(notFoundTemplate, "{{request_url}}", r.RequestURI)
  21. rel := getRootEscapeFromCurrentPath(r.RequestURI)
  22. notFoundTemplate = strings.ReplaceAll(notFoundTemplate, "{{root_escape}}", rel)
  23. w.WriteHeader(http.StatusNotFound)
  24. w.Write([]byte(notFoundTemplate))
  25. }
  26. } else {
  27. http.NotFound(w, r)
  28. }
  29. }
  30. func errorHandlePermissionDenied(w http.ResponseWriter, r *http.Request) {
  31. unauthorizedPage := "./web/SystemAO/unauthorized.html"
  32. if fs.FileExists(unauthorizedPage) {
  33. notFoundTemplateBytes, err := ioutil.ReadFile(unauthorizedPage)
  34. notFoundTemplate := string(notFoundTemplateBytes)
  35. if err != nil {
  36. http.NotFound(w, r)
  37. } else {
  38. //Replace the request URL inside the page
  39. notFoundTemplate = strings.ReplaceAll(notFoundTemplate, "{{request_url}}", r.RequestURI)
  40. rel := getRootEscapeFromCurrentPath(r.RequestURI)
  41. notFoundTemplate = strings.ReplaceAll(notFoundTemplate, "{{root_escape}}", rel)
  42. w.WriteHeader(http.StatusUnauthorized)
  43. w.Write([]byte(notFoundTemplate))
  44. }
  45. } else {
  46. http.Error(w, "Not authorized", http.StatusUnauthorized)
  47. }
  48. }
  49. //Get escape root path, example /asd/asd => ../../
  50. func getRootEscapeFromCurrentPath(requestURL string) string {
  51. rel := ""
  52. if !strings.Contains(requestURL, "/") {
  53. return ""
  54. }
  55. splitter := requestURL
  56. if splitter[len(splitter)-1:] != "/" {
  57. splitter = splitter + "/"
  58. }
  59. for i := 0; i < len(strings.Split(splitter, "/"))-2; i++ {
  60. rel += "../"
  61. }
  62. return rel
  63. }