2

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?

user3918985
  • 4,278
  • 9
  • 42
  • 63

3 Answers3

6

Resolved.

I added this in func main()

router.PathPrefix("/").Handler(http.FileServer(http.Dir("./layout/")))
user3918985
  • 4,278
  • 9
  • 42
  • 63
0

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))))
Jorn
  • 457
  • 7
  • 11
0

In your Go file:

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))))
}
// Add route prefix for stylesheets directory
router.PathPrefix("/stylesheets/").Handler(http.StripPrefix("/stylesheets/",
    http.FileServer(http.Dir(staticDirectory+"stylesheets/"))))
}

Then update your htmlfile with this link:

<link rel="stylesheet" type="text/css" href="/stylesheets/log.css">
dom1
  • 425
  • 1
  • 2
  • 19