error.go 1.9 KB

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