[英]Serve html,css,js files under subpath in go mux
I want to display a compiled angular project under a subpath (eg http://localhost:3000/app/) with go mux我想用 go 多路复用器在子路径下显示编译的 angular 项目(例如 http://localhost:3000/app/)
It works as expected without the subpath "app/"在没有子路径“app/”的情况下,它可以按预期工作
But when I add the subpath with http.StripPrexix("/app/, ..) Handler only index html is found and rendered but without all css, js files..但是当我添加带有 http.StripPrexix("/app/, ..) 的子路径时,处理程序仅索引 html 被发现并呈现,但没有所有 css 文件。
Test code测试代码
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索引.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>
Working Project Download工作项目下载
This project also includes the static files to serve该项目还包括 static 文件以提供服务
https://filehorst.de/d/dubJmmsz https://filehorst.de/d/dubJmmsz
Goal目标
Serve different projects under different paths服务不同路径下的不同项目
Following on this question 关注这个问题
What am I doing wrong?我究竟做错了什么?
How to serve the whole project under eg: localhost:3000/app/如何在 eg: localhost:3000/app/ 下为整个项目服务
Thegorilla mux docs mention how to handle Angular SPA applications. gorilla mux 文档提到如何处理 Angular SPA 应用程序。
However since you want to base your SPA root to a sub directory, you also need to do the changes in HTML/JS.但是,由于您希望将 SPA 根目录基于子目录,因此您还需要在 HTML/JS 中进行更改。 The base directory should be a variable that will be same as that of prefix of SPA.
基本目录应该是一个变量,与 SPA 的前缀相同。 This is more of a design problem I believe
我相信这更像是一个设计问题
Otherwise since your rest of the files other than index are resolved at root you need to fallback to "/" for rest of the files & have both configured.否则,由于除索引以外的文件的 rest 已在根目录下解析,因此您需要为文件的 rest 回退到“/”,并且都已配置。
router.PathPrefix("/app").Handler(spa)
router.PathPrefix("/").Handler(spa)
So try like below.所以尝试如下。 I tried your static folder with following:
我尝试了您的 static 文件夹,其中包含以下内容:
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())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.