登录
首页 >  Golang >  Go问答

如何使用 gorilla/mux 在 GO 中传递带有 html 的 bundle.js 文件

来源:stackoverflow

时间:2024-04-13 20:54:34 426浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《如何使用 gorilla/mux 在 GO 中传递带有 html 的 bundle.js 文件》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

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



  
    
    
     mern gen
  
  
app has crashed

目前我这样做是为了将两个文件传递到“/”网址

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

终于介绍完啦!小伙伴们,这篇关于《如何使用 gorilla/mux 在 GO 中传递带有 html 的 bundle.js 文件》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>