如何使用大猩猩/mux在GO中将我的捆绑.js文件与我的html一起交付



我正在尝试制作一个简单的服务器,其中包含Go后端和React前端。为此,我需要发送我的静态 html 和捆绑.js文件。她的网页

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">
<title>Mern Gen</title>
</head>
<body>
<main id='root'>
App has crashed
</main>
<script src="../public/bundle.js" 
type="text/javascript"></script>
</body>
</html>

目前我这样做是为了将两个文件都传送到"/"网址

bs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/public/", bs))
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)

我现在需要使用大猩猩/mux 来匹配这样的变量参数

r.HandleFunc("/loc/{id}", getLoc)

但是如果我这样做,我还必须从默认多路复用器更改为大猩猩路由器

r := mux.NewRouter()
bs := http.FileServer(http.Dir("public"))
r.Handle("/public/", http.StripPrefix("/public/", bs))
fs := http.FileServer(http.Dir("./static"))
r.Handle("/", fs)

这是行不通的。我收到一条错误消息,指出找不到我的捆绑包.js。如何使用大猩猩多路复用器执行此操作?

您应该使用PathPrefixpublic目录中提供文件:

r := mux.NewRouter()
bs := http.FileServer(http.Dir("public"))
r.PathPrefix("/public/").Handler(http.StripPrefix("/public/", bs))
fs := http.FileServer(http.Dir("./static"))
r.Handle("/", fs)
http.Handle("/", r)

参考大猩猩多路复用器文档

最新更新