Reputation: 1812
I'm using a router (httprouter) and would like to serve static files from root.
css file in
static/style.css
in template
<link href="./static/style.css" rel="stylesheet">
main.go
router := httprouter.New()
router.ServeFiles("/static/*filepath", http.Dir("/static/"))
router.GET("/", Index)
But http://localhost:3001/static/style.css gives me an 404 error and style in render page doesn't work too.
Upvotes: 4
Views: 5064
Reputation: 25399
This is how I got it working:
func main() {
router := httprouter.New()
router.GET("/", Index)
router.ServeFiles("/static/*filepath",http.Dir("static"))
log.Fatal(http.ListenAndServe(":3001", router))
}
Upvotes: 0
Reputation: 4179
Try to replace http.Dir("/static/")
with http.Dir("static")
(which will be the relative path to your static dir) or with http.Dir("/absolute/path/to/static")
. Your example with this single change works for me.
Also see httprouter's ServeFiles documentation:
func (r *Router) ServeFiles(path string, root http.FileSystem)
ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:
router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
This might also be of help - Third-party router and static files
I must admit that it's unclear to me why 'static' is needed twice. If I set http.Dir to "." it all works with the single difference that I need to navigate to localhost:3001/static/static/style.css
Upvotes: 6
Reputation: 8490
In call router.ServeFiles("/static/*filepath", http.Dir("/static/"))
second argument provide root and first arg define the path from that root. So , try
router.ServeFiles("*filepath", http.Dir("/static"))
without mentioning /static/ twice.
Upvotes: 2