Go: serve CSS files with gorilla mux

2019-05-31 18:45发布

问题:

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


标签: go gorilla