Home > Enterprise >  404 with http.FileServer with absolute path
404 with http.FileServer with absolute path

Time:01-16

I have a file C:\hello\index.go:

package main
import "net/http"

func main() {
   http.Handle("/assets", http.FileServer(http.Dir("assets")))
   println("ListenAndServe")
   http.ListenAndServe(":9000", nil)
}

I enter go run index.go, then make this request:

PS C:\> curl localhost:9000/assets/kitten.jpg
404 page not found

I know the path is valid:

PS C:\> curl -I file:/C:/hello/assets/kitten.jpg
Content-Length: 3000898
Accept-ranges: bytes
Last-Modified: Sun, 16 Jan 2022 01:14:58 GMT

I also tried these other lines:

http.Handle("/assets", http.FileServer(http.Dir(`C:\hello\assets`)))
http.Handle("/assets/", http.FileServer(http.Dir("assets")))
http.Handle("/assets/", http.FileServer(http.Dir(`C:\hello\assets`)))

but I get 404 every time. What am I doing wrong?

CodePudding user response:

This command:

http.Handle("/assets", http.FileServer(http.Dir("assets")))

Sets the filesystem root to assets, then the request is added on top of that. So if you make a request like this:

/assets/kitten.jpg

Then the server will look for a path like this:

assets/assets/kitten.jpg

I have seen some people suggest using StripPrefix, but this seems to do the job as well:

http.Handle("/assets/", http.FileServer(http.Dir(".")))

CodePudding user response:

Looks like you need to use the http.StripPrefix function.

Example similar to yours. Please note the trailing / I've added:

package main

import (
    "net/http"
)

func main() {
    http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
    println("ListenAndServe")
    http.ListenAndServe(":9000", nil)
}

Example from the docs:

package main

import (
    "net/http"
)

func main() {
    // To serve a directory on disk (/tmp) under an alternate URL
    // path (/tmpfiles/), use StripPrefix to modify the request
    // URL's path before the FileServer sees it:
    http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
}
  •  Tags:  
  • Related