使用Gorilla工具包为根URL提供静态内容 [英] Serving static content with a root URL with the Gorilla toolkit

查看:125
本文介绍了使用Gorilla工具包为根URL提供静态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Gorilla工具包的 mux 程序包在Go Web服务器中路由URL。使用这个问题作为指南我有下面的代码:

I am attempting to use the Gorilla toolkit's mux package to route URLs in a Go web server. Using this question as a guide I have the following Go code:

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

The Javascript and CSS files are referenced in index.html like this:

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

访问 http:// localhost :8100 在我的网络浏览器中, index.html 内容已成功发送,但是,所有 js css URL返回404s。

When I access http://localhost:8100 in my web browser the index.html content is delivered successfully, however, all the js and css URLs return 404s.

如何让程序为< c $ c> static 子目录?

推荐答案

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

I think you might be looking for 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.Handle("/", r)
    http.ListenAndServe(":8100", nil)
}

这篇关于使用Gorilla工具包为根URL提供静态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆