error.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package base
  2. import (
  3. "github.com/astaxie/beego"
  4. "github.com/astaxie/beego/logs"
  5. "net/http"
  6. config2 "nginx-ui/server/config"
  7. "nginx-ui/server/models"
  8. "nginx-ui/server/utils"
  9. "strings"
  10. )
  11. type ErrorController struct {
  12. beego.Controller
  13. WebPath string
  14. WebDir string
  15. }
  16. func getWebPath() string {
  17. config := config2.Config
  18. p := config.ContextPath
  19. if !strings.HasPrefix(p, "/") {
  20. p = "/" + p
  21. }
  22. if !strings.HasSuffix(p, "/") {
  23. p = p + "/"
  24. }
  25. return p
  26. }
  27. func (c *ErrorController) Error404() {
  28. if c.WebPath == "" {
  29. c.WebPath = getWebPath()
  30. }
  31. if c.WebDir == "" {
  32. c.WebDir = utils.GetStaticDir()
  33. }
  34. c.EnableRender = false
  35. request := c.Ctx.Request
  36. accept := request.Header.Get("accept")
  37. logs.Warn("404", request.RequestURI, accept)
  38. if strings.Contains(accept, "json") {
  39. c.Ctx.Output.SetStatus(http.StatusOK)
  40. c.Data["json"] = models.RespData{
  41. Code: 404,
  42. Msg: "API NOT FOUND!",
  43. }
  44. c.ServeJSON()
  45. } else if c.WebPath != request.RequestURI {
  46. c.EnableRender = true
  47. //c.Redirect(c.WebPath, http.StatusMovedPermanently)
  48. // 适配vue的history模式
  49. c.Ctx.Output.SetStatus(http.StatusOK)
  50. c.TplName = "index.html"
  51. } else {
  52. c.Data["json"] = models.RespData{
  53. Code: 404,
  54. Msg: "Not Found",
  55. }
  56. c.ServeJSON()
  57. }
  58. }