Files
bj_power/bj_power_wms_client/main.go
T
2026-08-28 15:06:01 +08:00

77 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"embed"
"flag"
"fmt"
"io/fs"
"net/http"
"path"
"strings"
"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)
})
}
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)
server.Start()
}