reactjs - 如何使用 gorilla/mux 在 GO 中将我的 bundle.js 文件与我的 html 一起交付

标签 reactjs go

我正在尝试制作一个带有 Go 后端和 React 前端的简单服务器。为此,我需要发送我的静态 html 和 bundle.js 文件。她是 html

<!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>

目前我这样做是为了将两个文件都传送到“/” url

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

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

我现在需要使用 gorilla/mux 来匹配这样的可变参数

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

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

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)

这行不通。我收到一条错误消息,指出找不到我的 bundle.js。我如何使用 gorilla mux 做到这一点?

最佳答案

您应该使用 PathPrefix 来提供 public 目录中的文件:

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)

引用Gorilla mux document

关于reactjs - 如何使用 gorilla/mux 在 GO 中将我的 bundle.js 文件与我的 html 一起交付,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51804258/

相关文章:

javascript - 全局变量存储在本地后如何访问它?

jquery - 如何在 Jquery 和 golang 中使用输入的 json 数据进行 ajax 调用?

戈朗 : Different AppEngine packages

linux - 使用Go生成适用于`/etc/shadow`的哈希密码字符串

reactjs - 当值更改时,HTML select onChange 不会触发

reactjs - 在ReactJS中使用createElement时如何写入data-remote ="true"?

templates - 文本模板中的线程安全映射

mongodb - Mgo 如何在嵌套数组中查找嵌套文档?

javascript - 尝试根据返回值过滤对象数组

asp.net - IdentityServer4 无法在生产环境中运行