2 Commits 3fc901a02c ... b22415ea8f

Author SHA1 Message Date
  tuonian b22415ea8f minor: 适应前端路由 3 weeks ago
  tuonian f89be7506c minor: 首页跳转问题 3 weeks ago
2 changed files with 64 additions and 20 deletions
  1. 54 0
      server/base/error.go
  2. 10 20
      server/routers/router.go

+ 54 - 0
server/base/error.go

@@ -0,0 +1,54 @@
+package base
+
+import (
+	"github.com/astaxie/beego"
+	"github.com/astaxie/beego/logs"
+	"net/http"
+	config2 "nginx-ui/server/config"
+	"nginx-ui/server/models"
+	"strings"
+)
+
+type ErrorController struct {
+	beego.Controller
+	WebPath string
+}
+
+func getWebPath() string {
+	config := config2.Config
+	p := config.ContextPath
+	if !strings.HasPrefix(p, "/") {
+		p = "/" + p
+	}
+	if !strings.HasSuffix(p, "/") {
+		p = p + "/"
+	}
+	return p
+}
+
+func (c *ErrorController) Error404() {
+
+	if c.WebPath == "" {
+		c.WebPath = getWebPath()
+	}
+
+	request := c.Ctx.Request
+
+	accept := request.Header.Get("accept")
+	logs.Warn("404", accept)
+	if strings.Contains(accept, "json") {
+		c.Data["json"] = models.RespData{
+			Code: -2,
+			Msg:  "server error",
+		}
+		c.ServeJSON()
+	} else if c.WebPath != request.RequestURI {
+		c.Redirect(c.WebPath, http.StatusMovedPermanently)
+	} else {
+		c.Data["json"] = models.RespData{
+			Code: 404,
+			Msg:  "Not Found",
+		}
+		c.ServeJSON()
+	}
+}

+ 10 - 20
server/routers/router.go

@@ -1,15 +1,13 @@
 package routers
 
 import (
-	"encoding/json"
 	"fmt"
 	"github.com/astaxie/beego"
 	"github.com/astaxie/beego/context"
 	"github.com/astaxie/beego/logs"
-	"net/http"
+	"nginx-ui/server/base"
 	config2 "nginx-ui/server/config"
 	"nginx-ui/server/middleware"
-	"nginx-ui/server/models"
 	"nginx-ui/server/modules/ldap"
 	"nginx-ui/server/modules/nginx/nginx_controller"
 	"nginx-ui/server/modules/oauth2"
@@ -78,25 +76,17 @@ func init() {
 	beego.Router(fmt.Sprintf("%s/config.js", config.ContextPath), &nginx_controller.ConfigController{})
 	// portal static assets
 	beego.SetStaticPath(config.ContextPath, "static/web")
+
+	webPrefix := config.ContextPath
+	if !strings.HasSuffix(webPrefix, "/") {
+		webPrefix = webPrefix + "/"
+	}
+
 	beego.Get("/", func(ctx *context.Context) {
-		ctx.Redirect(301, fmt.Sprintf("%s/index.html", config.ContextPath))
+		ctx.Redirect(301, webPrefix)
 	})
 
-	beego.ErrorHandler("404", func(writer http.ResponseWriter, request *http.Request) {
-		accept := request.Header.Get("accept")
-		logs.Warn("404", accept)
-		if strings.Contains(accept, "json") {
-			writer.Header().Set("content-type", "application/json")
-			writer.WriteHeader(200)
-			resp := models.RespData{
-				Code: -2,
-				Msg:  "server error",
-			}
-			str, _ := json.Marshal(&resp)
-			writer.Write(str)
-		} else {
-			writer.WriteHeader(404)
-			writer.Write([]byte(""))
-		}
+	beego.ErrorController(&base.ErrorController{
+		WebPath: webPrefix,
 	})
 }