Go: serve CSS files with gorilla mux

杀马特。学长 韩版系。学妹 提交于 2019-12-08 03:52:57

问题


I have this directory structure and I'm using Gorilla mux:

Directory structure

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

Following the advice here: http://www.shakedos.com/2014/Feb/08/serving-static-files-with-go.html I did this:

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)
}

Still I can't link the CSS file. What am I doing wrong?


回答1:


Resolved.

I added this in func main()

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



回答2:


You can do this in a easier way without adding the extra line in main():

inside ServeStatic: add this: "."+ before pathValue

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


来源:https://stackoverflow.com/questions/25347963/go-serve-css-files-with-gorilla-mux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!