添加强制路由转发 配合vue的静态文件

This commit is contained in:
eson 2023-07-11 16:50:18 +08:00
parent 43e2e835eb
commit aabf8faca7

View File

@ -6,7 +6,9 @@ import (
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
)
@ -15,21 +17,22 @@ var Backends []*Backend
func main() {
rootDir := "../server" // Change this to your root directory
vueBuild := "/home/eson/workspace/fusenpack-vue-created"
apiURL, err := url.Parse("http://localhost:9900")
if err != nil {
panic(err)
}
mux := http.NewServeMux()
// Define the static file server that serves the Vue dist folder
fs := http.FileServer(http.Dir(vueBuild))
// Define a handler function for the Vue static assets
mux.Handle("/", http.StripPrefix("/", fs))
results := GetZeroInfo(rootDir)
var allRoutes map[string]bool = make(map[string]bool)
for _, result := range results {
fmt.Printf("FolderName: %s, Host: %s, Port: %d, PrefixRoute: %v\n", result.FolderName, result.Host, result.Port, result.PrefixRoute)
var routes []string
for k := range result.PrefixRoute {
routes = append(routes, k)
allRoutes[k] = true
}
Backends = append(Backends,
@ -38,6 +41,35 @@ func main() {
routes...))
}
// Define the static file server that serves the Vue dist folder
fs := http.FileServer(http.Dir(vueBuild))
// Define a handler function for the Vue static assets
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var prefix string
idx := strings.Index(r.URL.Path[1:], "/")
if idx == -1 {
prefix = r.URL.Path
} else {
prefix = r.URL.Path[:idx]
}
// log.Println(r.URL.Path, prefix)
if _, ok := allRoutes[prefix]; ok {
proxy := httputil.NewSingleHostReverseProxy(apiURL)
proxy.ServeHTTP(w, r)
} else {
// fs.ServeHTTP(w, r)
if strings.HasPrefix(prefix, "/type") {
http.ServeFile(w, r, vueBuild+"/index.html")
} else if strings.HasPrefix(prefix, "/dt-") {
http.ServeFile(w, r, vueBuild+"/index.html")
} else {
fs.ServeHTTP(w, r)
}
}
})
ServerAddress := ":9900"
log.Println("listen on ", ServerAddress)
log.Fatal(http.ListenAndServe(ServerAddress, mux))