我想用go mux在子路径(如http://localhost:3000/app/)下显示编译后的角项目。
它在没有子路径"app/“的情况下正常工作。
但是当我用http.StripPrexix("/app/,.) Handler添加子路径时,只找到并呈现索引html,但是没有所有css、js文件。
测试代码
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
mux := mux.NewRouter()
fs := http.FileServer(http.Dir("./static/"))
// Serve static files
mux.PathPrefix("/app/").Handler(http.StripPrefix("/app/", fs))
log.Println("Listening...")
http.ListenAndServe(":3000", mux)
}
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TestProject</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.3ff695c00d717f2d2a11.css"></head>
<body>
<h1>Should work</h1>
<app-root></app-root>
<script src="runtime.359d5ee4682f20e936e9.js" defer></script><script src="polyfills.bf99d438b005d57b2b31.js" defer></script><script src="main.5dd083c1a27b2a7e410a.js" defer></script></body>
</html>
工作项目下载
此项目还包括要服务的静态文件。
https://filehorst.de/d/dubJmmsz
目标
在不同的路径下为不同的项目服务
我做错什么了?
如何服务整个项目,例如: localhost:3000/app/
发布于 2020-12-11 10:15:25
大猩猩医学博士提到了如何处理角SPA应用程序。
但是,由于您希望将SPA根目录根目录设置为子目录,所以还需要对/JS进行更改。基目录应该是与SPA前缀相同的变量。这更像是一个设计问题,我相信
否则,由于除索引之外的其他文件都是在根解析的,所以对于其余的文件,您需要回退到"/“,这两个文件都已经配置好了。
router.PathPrefix("/app").Handler(spa)
router.PathPrefix("/").Handler(spa)
所以试试下面的样子。我尝试了您的静态文件夹如下:
package main
import (
"log"
"net/http"
"os"
"path/filepath"
"time"
"github.com/gorilla/mux"
)
type spaHandler struct {
staticPath string
indexPath string
}
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// get the absolute path to prevent directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// prepend the path with the path to the static directory
path = filepath.Join(h.staticPath, path)
// check whether a file exists at the given path
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
return
} else if err != nil {
// if we got an error (that wasn't that the file doesn't exist) stating the
// file, return a 500 internal server error and stop
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// otherwise, use http.FileServer to serve the static dir
http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}
func main() {
router := mux.NewRouter()
spa := spaHandler{staticPath: "static", indexPath: "index.html"}
router.PathPrefix("/app").Handler(spa)
srv := &http.Server{
Handler: router,
Addr: ":3000",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
https://stackoverflow.com/questions/65248991
复制相似问题