浏览代码

优化代码

niujiuru 3 周之前
父节点
当前提交
63ffa189ae
共有 3 个文件被更改,包括 67 次插入41 次删除
  1. 9 6
      web-ui.service/page5_handler.go
  2. 32 16
      web-ui.service/web/static/js/router.js
  3. 26 19
      web-ui.service/web_handler.go

+ 9 - 6
web-ui.service/page5_handler.go

@@ -6,6 +6,7 @@ import (
 	"net/http"
 	"os"
 	"os/exec"
+	"strconv"
 	"time"
 )
 
@@ -62,7 +63,7 @@ func restartCameraService(w http.ResponseWriter, r *http.Request) {
 }
 
 func cameraStatusHandler(w http.ResponseWriter, r *http.Request) {
-	var countAll, countHK, countDH string
+	var countHK, countDH string
 	var power struct {
 		Enable string `json:"enable"`
 	}
@@ -70,11 +71,6 @@ func cameraStatusHandler(w http.ResponseWriter, r *http.Request) {
 
 	avar1, avar2, avar3, avar4, avar5, avar6 := noValue, noValue, noValue, noValue, noValue, noValue
 
-	if callRPCResult(r.Context(), 7003, "core.getSupportedCameraCount", map[string]string{"type": "all"}, &countAll) == nil {
-		avar1 = "🟢正常"
-		avar2 = countAll
-	}
-
 	if callRPCResult(r.Context(), 7003, "core.getSupportedCameraCount", map[string]string{"type": "hk"}, &countHK) == nil {
 		avar3 = countHK
 	}
@@ -83,6 +79,13 @@ func cameraStatusHandler(w http.ResponseWriter, r *http.Request) {
 		avar4 = countDH
 	}
 
+	if avar3 != noValue && avar4 != noValue {
+		hk, _ := strconv.Atoi(avar3)
+		dh, _ := strconv.Atoi(avar4)
+		avar2 = strconv.Itoa(hk + dh)
+		avar1 = "🟢正常"
+	}
+
 	callRPCResult(r.Context(), 7003, "core.getGigeCameraPower", nil, &power)
 	if power.Enable == "true" {
 		avar5 = "🟢打开"

+ 32 - 16
web-ui.service/web/static/js/router.js

@@ -10,6 +10,7 @@ const routes = {
 };
 
 let currentPage = null;
+let loadingPage = false;
 
 const pageHandlers = {
   page1: {
@@ -41,7 +42,8 @@ const pageHandlers = {
 };
 
 function clearOldScripts() {
-  document.querySelectorAll("script[data-dynamic='1']").forEach(s => s.remove());
+  document.querySelectorAll("script[data-dynamic='1']")
+    .forEach(s => s.remove());
 }
 
 function runScripts(container) {
@@ -66,40 +68,54 @@ async function loadPage(name) {
   const url = routes[name];
 
   if (!url) {
-    view.innerHTML = "<div class='card'>无法找到页面</div>";
+    view.innerHTML = "无法找到页面";
     return;
   }
 
-  try {
-    const res = await fetch(url, { credentials: "include" });
-    const html = await res.text();
+  if (loadingPage) {
+    return;
+  }
 
-    if (html.includes("login.html") || html.includes("登录")) {
-      window.location.href = "/";
-      return;
-    }
+  if (currentPage === name) {
+    return;
+  }
 
-    const temp = document.createElement("div");
-    temp.innerHTML = html;
+  try {
+    loadingPage = true;
 
     if (currentPage && pageHandlers[currentPage]?.exit) {
+      console.log("exit:", currentPage);
       pageHandlers[currentPage].exit();
     }
 
     clearOldScripts();
 
-    view.innerHTML = "";
-    view.appendChild(temp);
+    const res = await fetch(url, {
+      credentials: "include"
+    });
+
+    const html = await res.text();
+
+    if (html.includes("login.html") || html.includes("登录")) {
+      window.location.href = "/";
+      return;
+    }
+
+    view.innerHTML = html;
+
+    runScripts(view);
 
-    runScripts(temp);
-    
     currentPage = name;
 
     if (pageHandlers[name]?.init) {
+      console.log("init:", name);
       pageHandlers[name].init();
     }
+
   } catch (e) {
     console.error("loadPage error:", e);
-    view.innerHTML = "<div class='card'>页面加载失败</div>";
+    view.innerHTML = "页面加载失败";
+  } finally {
+    loadingPage = false;
   }
 }

+ 26 - 19
web-ui.service/web_handler.go

@@ -148,8 +148,7 @@ var logFiles = map[string]string{
 func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
 	unit := r.URL.Query().Get("unit")
 	if unit == "" {
-		http.Error(w, "missing unit",
-			http.StatusBadRequest)
+		http.Error(w, "missing unit", http.StatusBadRequest)
 		return
 	}
 
@@ -160,8 +159,7 @@ func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
 
 	flusher, ok := w.(http.Flusher)
 	if !ok {
-		http.Error(w, "not supported",
-			http.StatusInternalServerError)
+		http.Error(w, "not supported", http.StatusInternalServerError)
 		return
 	}
 
@@ -202,8 +200,9 @@ func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
+	id := time.Now().UnixNano()
 	if true {
-		baseapp.Logger.Debugf("[服务日志流启动] unit=%s", unit)
+		baseapp.Logger.Debugf("[服务日志流启动] id=%d unit=%s", id, unit)
 	}
 
 	defer func() {
@@ -212,23 +211,33 @@ func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
 		}
 		cmd.Wait()
 
-		baseapp.Logger.Debugf("[服务日志流关闭] unit=%s", unit)
+		baseapp.Logger.Debugf("[服务日志流关闭] id=%d unit=%s", id, unit)
 	}()
 
-	scanner := bufio.NewScanner(stdout)
+	lines := make(chan string, 100)
 
-	for scanner.Scan() {
-		select {
-		case <-r.Context().Done():
-			return
-		default:
+	go func() {
+		scanner := bufio.NewScanner(stdout)
+		scanner.Buffer(make([]byte, 1024), 1024*1024)
+		for scanner.Scan() {
+			lines <- scanner.Text()
 		}
+		close(lines)
+	}()
 
-		if _, err := fmt.Fprintf(w, "data: %s\n\n", scanner.Text()); err != nil {
+	for {
+		select {
+		case <-r.Context().Done():
 			return
+		case line, ok := <-lines:
+			if !ok {
+				return
+			}
+			if _, err := fmt.Fprintf(w, "data: %s\n\n", line); err != nil {
+				return
+			}
+			flusher.Flush()
 		}
-
-		flusher.Flush()
 	}
 }
 
@@ -267,7 +276,6 @@ func callRPCResult(ctx context.Context, port int, method string, params any, res
 
 	client, err := jsonrpc2.NewRPCClient(url)
 	if err != nil {
-		baseapp.Logger.Errorf("[执行RPC错误] %s err=%v\n", method, err)
 		return err
 	}
 
@@ -276,7 +284,7 @@ func callRPCResult(ctx context.Context, port int, method string, params any, res
 		return err
 	}
 
-	baseapp.Logger.Debugf("[发送RPC应答] %s result=%s\n", method, string(resp.Result))
+	baseapp.Logger.Debugf("[发送RPC应答] %s result=%s err=%v\n", method, string(resp.Result), resp.Error)
 
 	return json.Unmarshal(resp.Result, result)
 }
@@ -295,12 +303,11 @@ func callRPCResponse(w http.ResponseWriter, r *http.Request, port int, method st
 
 	resp, err := client.Call(r.Context(), method, params)
 	if err != nil {
-		baseapp.Logger.Errorf("[执行RPC错误] %s err=%v\n", method, err)
 		http.Error(w, err.Error(), http.StatusInternalServerError)
 		return
 	}
 
-	baseapp.Logger.Debugf("[发送RPC应答] %s result=%s\n", method, string(resp.Result))
+	baseapp.Logger.Debugf("[发送RPC应答] %s result=%s err=%v\n", method, string(resp.Result), resp.Error)
 
 	w.Header().Set("Content-Type", "application/json; charset=utf-8")
 	json.NewEncoder(w).Encode(resp.Result)