Forráskód Böngészése

minor: 适应前端路由

tuonian 4 hete
szülő
commit
b22415ea8f
2 módosított fájl, 57 hozzáadás és 22 törlés
  1. 54 0
      server/base/error.go
  2. 3 22
      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()
+	}
+}

+ 3 - 22
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"
@@ -87,25 +85,8 @@ func init() {
 	beego.Get("/", func(ctx *context.Context) {
 		ctx.Redirect(301, webPrefix)
 	})
-	beego.Get(config.ContextPath+"/*", func(ctx *context.Context) {
-		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,
 	})
 }