Files
bj_power/bj_power_wms_client/main.go
T

106 lines
2.6 KiB
Go
Raw Normal View History

2026-08-28 15:06:01 +08:00
package main
import (
"embed"
"flag"
"fmt"
"io/fs"
"net/http"
2026-08-29 15:30:25 +08:00
"os/exec"
2026-08-28 15:06:01 +08:00
"path"
2026-08-29 15:30:25 +08:00
"runtime"
2026-08-28 15:06:01 +08:00
"strings"
2026-08-29 15:30:25 +08:00
"time"
2026-08-28 15:06:01 +08:00
"bj_power_wms_client/internal/config"
"bj_power_wms_client/internal/proxy"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest"
)
//go:embed all:web/static
var webFS embed.FS
var configFile = flag.String("f", "etc/bj_power_wms_client.yaml", "the config file")
// newStaticHandler 嵌入式静态文件:命中则直接返回;未命中的非 /api 路径
// 回退到 index.htmlSPA history 路由),由浏览器端 Vue Router 接管。
func newStaticHandler(fsys embed.FS) http.Handler {
sub, err := fs.Sub(fsys, "web/static")
if err != nil {
panic(fmt.Sprintf("嵌入静态目录不可用: %v", err))
}
fileServer := http.FileServer(http.FS(sub))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
if name == "" {
name = "index.html"
}
if f, openErr := sub.Open(name); openErr == nil {
f.Close()
fileServer.ServeHTTP(w, r)
return
}
r2 := r.Clone(r.Context())
r2.URL.Path = "/"
fileServer.ServeHTTP(w, r2)
})
}
2026-08-29 15:30:25 +08:00
// openBrowser 调用系统默认浏览器打开 url
func openBrowser(url string) {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
case "darwin":
cmd = exec.Command("open", url)
default:
cmd = exec.Command("xdg-open", url)
}
_ = cmd.Start()
}
2026-08-28 15:06:01 +08:00
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
apiProxy := proxy.New(c.WmsAddr, c.ApiToken)
staticHandler := newStaticHandler(webFS)
// 兜底路由:/api/* 反向代理到 WMS 后端,其余走嵌入式静态资源(未命中回退 index.html)
notFound := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api") {
if r.URL.Path == "/api" || strings.HasPrefix(r.URL.Path, "/api/") {
apiProxy.ServeHTTP(w, r)
return
}
http.NotFound(w, r)
return
}
staticHandler.ServeHTTP(w, r)
})
server := rest.MustNewServer(c.RestConf, rest.WithNotFoundHandler(notFound))
defer server.Stop()
fmt.Printf("Starting bj_power_wms_client at :%d...\n", c.Port)
logx.Infof("Starting bj_power_wms_client at :%d...", c.Port)
2026-08-29 15:30:25 +08:00
// 服务起来后自动打开浏览器访问前端
host := c.Host
if host == "0.0.0.0" || host == "" {
host = "127.0.0.1"
}
go func() {
time.Sleep(time.Second)
openBrowser(fmt.Sprintf("http://%s:%d", host, c.Port))
}()
2026-08-28 15:06:01 +08:00
server.Start()
2026-08-29 15:30:25 +08:00
}