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)
}
The directory structure is:
...
main.go
static\
| index.html
| js\
| <js files>
| css\
| <css files>
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>
...
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.
How can I get the program to serve files out of static
sub-directories?
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.ListenAndServe(":8100", r)
}
After a lot of trial and error, both above answers helped me in coming up with what worked for me. I have static folder in web app's root directory.
Along with PathPrefix
I had to use StripPrefix
for getting route to work recursively.
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
s := http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))
r.PathPrefix("/static/").Handler(s)
http.Handle("/", r)
err := http.ListenAndServe(":8081", nil)
}
I hope it helps somebody else having problems.
I have this code here that works quite nice and is re-usable.
func ServeStatic(router *mux.Router, staticDirectory string) {
staticPaths := map[string]string{
"styles": staticDirectory + "/styles/",
"bower_components": staticDirectory + "/bower_components/",
"images": staticDirectory + "/images/",
"scripts": staticDirectory + "/scripts/",
}
for pathName, pathValue := range staticPaths {
pathPrefix := "/" + pathName + "/"
router.PathPrefix(pathPrefix).Handler(http.StripPrefix(pathPrefix,
http.FileServer(http.Dir(pathValue))))
}
}
router := mux.NewRouter()
ServeStatic(router, "/static/")
Try this:
fileHandler := http.StripPrefix("/static/", http.FileServer(http.Dir("/absolute/path/static")))
http.Handle("/static/", fileHandler)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With