web-applications - 使用 Gorilla 工具包通过根 URL 提供静态内容

标签 web-applications go mux

我正在尝试使用 Gorilla 工具包的 mux package在 Go Web 服务器中路由 URL。使用 this question作为指导,我有以下 Go 代码:

func main() {
    r := mux.NewRouter()
    r.Handle("/", http.FileServer(http.Dir("./static/")))
    r.HandleFunc("/search/{searchTerm}", Search)
    r.HandleFunc("/load/{dataId}", Load)
    http.Handle("/", r)
    http.ListenAndServe(":8100", nil)
}

目录结构为:

...
main.go
static\
  | index.html
  | js\
     | <js files>
  | css\
     | <css files>

Javascript 和 CSS 文件在 index.html 中引用如下:

...
<link rel="stylesheet" href="css/redmond/jquery-ui.min.css"/>
<script src="js/jquery.min.js"></script>
...

当我在网络浏览器中访问 http://localhost:8100 时,index.html 内容已成功交付,但是,所有 jscss URL 返回 404。

如何让程序从 static 子目录中提供文件?

最佳答案

我想你可能正在寻找 PathPrefix...

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/search/{searchTerm}", Search)
    r.HandleFunc("/load/{dataId}", Load)
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))
    http.ListenAndServe(":8100", r)
}

关于web-applications - 使用 Gorilla 工具包通过根 URL 提供静态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15834278/

相关文章:

go - Go Lang 中更漂亮的方法

tcp - 不同 Goroutine 中的 ZeroMQ 上下文如何通信?

json - 使用Golang的示例JSON响应

ruby-on-rails - 在一个 .each 循环中查询多个表

mysql - 通过 Hibernate 将 webapp 连接到 docker mysql 容器的巨大延迟

php - 立即或在填写表格后将条目添加到数据库中

web-applications - SproutCore新手困惑

github - 支持 GitHub

go - Web 进程在启动 golang 后 60 秒内未能绑定(bind)到 $PORT

image-processing - 从通过混合一堆图像创建的视频中提取帧正在改变帧的完整性