【问题标题】:Go: serve CSS files with gorilla muxGo:使用 gorilla mux 提供 CSS 文件
【发布时间】:2014-08-17 09:32:03
【问题描述】:

我有这个目录结构,我正在使用 Gorilla mux:

目录结构

twitter
    layout
        stylesheets
            log.css
        log.html
    twitter.go

按照这里的建议:http://www.shakedos.com/2014/Feb/08/serving-static-files-with-go.html 我这样做了:

var router = mux.NewRouter()

func ServeStatic(router *mux.Router, staticDirectory string) {
    staticPaths := map[string]string{
        "styles": staticDirectory + "stylesheets",
        }
    for pathName, pathValue := range staticPaths {
        pathPrefix := "/" + pathName + "/"
        router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
        http.FileServer(http.Dir(pathValue))))
    }
}

var staticDirectory = "/layout/"

func main() {
    (//other code)
    ServeStatic(router, staticDirectory)
}

我仍然无法链接 CSS 文件。我做错了什么?

【问题讨论】:

  • 如何访问 CSS 文件?您可以粘贴您尝试访问的网址吗?

标签: go gorilla


【解决方案1】:

已解决。

我在 func main() 中添加了这个

router.PathPrefix("/").Handler(http.FileServer(http.Dir("./layout/")))

【讨论】:

    【解决方案2】:

    你可以用一种更简单的方式做到这一点,而无需在 main() 中添加额外的行:

    在 ServeStatic 内部: 在 pathValue 之前添加:"."+

    router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
                http.FileServer(http.Dir("."/pathValue))))
    

    【讨论】: