瀏覽代碼

整体优化调整代码结构

niujiuru 2 天之前
父節點
當前提交
b07a46502e

app-install.service/rpc_handlers.go → app-install.service/rpc_handler.go


camera-capture.service/rpc_handlers.go → camera-capture.service/rpc_handler.go


gnss.service/rpc_handlers.go → gnss.service/rpc_handler.go


networkd.service/rpc_handlers.go → networkd.service/rpc_handler.go


servicelib/rpc_handlers.go → servicelib/rpc_handler.go


system-metrics.service/rpc_handlers.go → system-metrics.service/rpc_handler.go


timesyncd.service/rpc_handlers.go → timesyncd.service/rpc_handler.go


upgrade.service/rpc_handlers.go → upgrade.service/rpc_handler.go


+ 0 - 1
web-ui.service/web/static/css/page2.css

@@ -162,4 +162,3 @@
 .log-card .output {
     padding-bottom: 32px;
 }
-

+ 2 - 2
web-ui.service/web/static/js/app.js

@@ -24,7 +24,7 @@ document.addEventListener("DOMContentLoaded", () => {
 });
 
 function logout() {
-  window.location.href = "/logout";
+  window.location.href = "/api/auth/logout";
 }
 
 function setIMEI(imei) {
@@ -36,7 +36,7 @@ function setIMEI(imei) {
 
 async function fetchIMEI() {
   try {
-    const res = await fetch("/getIMEI");
+    const res = await fetch("/api/device/imei");
 
     if (!res.ok) {
       throw new Error("http error");

+ 5 - 5
web-ui.service/web/static/js/log-stream.js

@@ -38,9 +38,9 @@ const monthMap = {
 
 function formatLog(line) {
     return line.replace(
-        /^(\w{3})\s+(\d{1,2})\s+(\d{2}:\d{2}:\d{2})\s+\S+\s+[^\s]+\[\d+\]:\s+\[([a-z]+)\]:\s+\[([^\]]+)\](.*)/i,
-        (_, mon, day, time, level, module, msg) =>
-            `${monthMap[mon]}-${day.padStart(2, '0')} ${time} ${level.toUpperCase()} [${module}]${msg}`
+        /^(\w{3})\s+(\d{1,2})\s+(\d{2}:\d{2}:\d{2})\s+\S+\s+[^\s]+\[\d+\]:\s+\[([a-z]+)\]:\s+\[[^\]]+\](.*)/i,
+        (_, mon, day, time, level, msg) =>
+            `${monthMap[mon]}-${day.padStart(2, '0')} ${time} ${level.toUpperCase()}${msg}`
     );
 }
 
@@ -66,7 +66,7 @@ function connectLog(unit, target) {
     el.textContent = "";
 
     const source = new EventSource(
-        `/log?unit=${encodeURIComponent(unit)}`
+        `/api/service/log?unit=${encodeURIComponent(unit)}`
     );
 
     logSource = source;
@@ -88,7 +88,7 @@ function connectLog(unit, target) {
         el.innerHTML = logLines
             .map(formatLog)
             .map(colorLog)
-            .join("<br>") + "<br><br>";
+            .join("<br>") + "<br><br><br>";
 
         el.scrollTop = el.scrollHeight;
     };

+ 1 - 1
web-ui.service/web/static/js/login.js

@@ -15,7 +15,7 @@ async function loginHandler(e) {
     const username = document.getElementById("username")?.value || "";
     const password = document.getElementById("password")?.value || "";
 
-    const res = await fetch("/login", {
+    const res = await fetch("/api/auth/login", {
         method: "POST",
         headers: {
             "Content-Type": "application/json"

+ 3 - 3
web-ui.service/web/static/js/page2.js

@@ -26,7 +26,7 @@ async function apiGetRetry(url, retry = false) {
 
 function getNetInfo1() {
   document.getElementById("text1").innerText = "";
-  apiGetRetry("/api/net/interfaces")
+  apiGetRetry("/api/network/interfaces")
     .then(data => {
       document.getElementById("text1").innerText = data;
     })
@@ -37,7 +37,7 @@ function getNetInfo1() {
 
 function getNetInfo2() {
   document.getElementById("text2").innerText = "";
-  apiGetRetry("/api/net/routes")
+  apiGetRetry("/api/network/routes")
     .then(data => {
       document.getElementById("text2").innerText = data;
     })
@@ -48,7 +48,7 @@ function getNetInfo2() {
 
 function getNetInfo3() {
   document.getElementById("text3").innerText = "";
-  apiGetRetry("/api/net/dns")
+  apiGetRetry("/api/network/dns")
     .then(data => {
       document.getElementById("text3").innerText = data;
     })

+ 22 - 22
web-ui.service/web_handlers.go

@@ -118,28 +118,7 @@ func (ui *WebUI) rootHandler(w http.ResponseWriter, r *http.Request) {
 	http.NotFound(w, r)
 }
 
-func runShellAndWrite(w http.ResponseWriter, cmd string) {
-	out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
-	if err != nil {
-		http.Error(w, err.Error()+"\n"+string(out), http.StatusInternalServerError)
-		return
-	}
-	w.Write(out)
-}
-
-func netInterfaces(w http.ResponseWriter, r *http.Request) {
-	runShellAndWrite(w, "ifconfig")
-}
-
-func netRoutes(w http.ResponseWriter, r *http.Request) {
-	runShellAndWrite(w, "route -n")
-}
-
-func netDNS(w http.ResponseWriter, r *http.Request) {
-	runShellAndWrite(w, "cat /etc/resolv.conf")
-}
-
-func logHandler(w http.ResponseWriter, r *http.Request) {
+func serviceLogHandler(w http.ResponseWriter, r *http.Request) {
 	unit := r.URL.Query().Get("unit")
 	if unit == "" {
 		http.Error(w, "missing unit",
@@ -205,3 +184,24 @@ func logHandler(w http.ResponseWriter, r *http.Request) {
 		flusher.Flush()
 	}
 }
+
+func runShellAndWrite(w http.ResponseWriter, cmd string) {
+	out, err := exec.Command("sh", "-c", cmd).CombinedOutput()
+	if err != nil {
+		http.Error(w, err.Error()+"\n"+string(out), http.StatusInternalServerError)
+		return
+	}
+	w.Write(out)
+}
+
+func netInterfaces(w http.ResponseWriter, r *http.Request) {
+	runShellAndWrite(w, "ifconfig")
+}
+
+func netRoutes(w http.ResponseWriter, r *http.Request) {
+	runShellAndWrite(w, "route -n")
+}
+
+func netDNS(w http.ResponseWriter, r *http.Request) {
+	runShellAndWrite(w, "cat /etc/resolv.conf")
+}

+ 51 - 0
web-ui.service/web_route.go

@@ -0,0 +1,51 @@
+package main
+
+import "net/http"
+
+type Route struct {
+	Path    string
+	Handler http.HandlerFunc
+}
+
+var routes = []Route{
+	{
+		"/api/auth/login",
+		loginHandler,
+	},
+
+	{
+		"/api/auth/logout",
+		logoutHandler,
+	},
+
+	{
+		"/api/device/imei",
+		getIMEIHandler,
+	},
+
+	{
+		"/api/service/log",
+		serviceLogHandler,
+	},
+
+	{
+		"/api/network/interfaces",
+		netInterfaces,
+	},
+
+	{
+		"/api/network/routes",
+		netRoutes,
+	},
+
+	{
+		"/api/network/dns",
+		netDNS,
+	},
+}
+
+func registerRoutes(mux *http.ServeMux) {
+	for _, r := range routes {
+		mux.HandleFunc(r.Path, r.Handler)
+	}
+}

+ 38 - 20
web-ui.service/web_ui.go

@@ -1,18 +1,20 @@
 package main
 
 import (
+	"context"
 	"embed"
 	"io/fs"
 	"net/http"
+	"time"
 )
 
 //go:embed web/*
 var webRootFS embed.FS
 
 type WebUI struct {
-	fs   fs.FS
-	addr string
-	mux  *http.ServeMux
+	fs     fs.FS
+	mux    *http.ServeMux
+	server *http.Server
 }
 
 func NewWebUI(addr string) (*WebUI, error) {
@@ -23,26 +25,42 @@ func NewWebUI(addr string) (*WebUI, error) {
 
 	mux := http.NewServeMux()
 
-	fs := http.FileServer(http.FS(sub))
-	mux.Handle("/static/css/", fs) ////////////// 页面样式
-	mux.Handle("/static/js/", fs)  ////////////// 页面脚本
-	/////////////////////////////////////////////////////
-	mux.HandleFunc("/login", loginHandler)   //// 登录接口
-	mux.HandleFunc("/logout", logoutHandler) //// 注销接口
-	/////////////////////////////////////////////////////
-	mux.HandleFunc("/getIMEI", getIMEIHandler) // 唯一编号
-	/////////////////////////////////////////////////////
-	mux.HandleFunc("/log", logHandler) ////////// 服务日志
-	/////////////////////////////////////////////////////
-	mux.HandleFunc("/api/net/interfaces", netInterfaces)
-	mux.HandleFunc("/api/net/routes", netRoutes)
-	mux.HandleFunc("/api/net/dns", netDNS)
-
-	return &WebUI{fs: sub, addr: addr, mux: mux}, nil
+	static := http.FileServer(http.FS(sub))
+
+	mux.Handle(
+		"/static/",
+		static,
+	)
+
+	registerRoutes(mux)
+
+	return &WebUI{
+		fs:  sub,
+		mux: mux,
+		server: &http.Server{
+			Addr:    addr,
+			Handler: mux,
+		},
+	}, nil
 }
 
 func (ui *WebUI) Start() error {
 	startSessionCleaner() // session过期自动回收
 	ui.mux.HandleFunc("/", ui.rootHandler)
-	return http.ListenAndServe(ui.addr, ui.mux)
+	return ui.server.ListenAndServe()
+}
+
+func (ui *WebUI) Stop() error {
+	if ui.server == nil {
+		return nil
+	}
+
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+
+	if err := ui.server.Shutdown(ctx); err != nil {
+		ui.server.Close()
+		return err
+	}
+	return nil
 }