There seems to be two ways to configure the mux to serve static content in Gorilla Mux(highlighted in blue)
package main
import (
"github.com/gorilla/mux"
"net/http"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
//This won't work
//http.Handle("/static/", http.FileServer(http.Dir("./static/")))
//These will work
//first alternative
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
//second alternative
r.PathPrefix("/images/").Handler(http.StripPrefix("/images/",
http.FileServer(http.Dir("images/"))))
http.Handle("/", r)
http.ListenAndServe(":3000", nil)
}
func HomeHandler(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte("You are at /"))
}
1 comment:
Awesome! Thanks.
Post a Comment