Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Httprouter trouble with static files

Tags:

go

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.

like image 497
Croaton Avatar asked Oct 17 '25 10:10

Croaton


1 Answers

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

like image 156
Makpoc Avatar answered Oct 19 '25 00:10

Makpoc