Home > Back-end >  go:embed fs only works for the root with http server?
go:embed fs only works for the root with http server?

Time:08-04

I have the following directory structure:

web/
  dist/
    index.html
main.go

the content of main.go:

package main

import (
    "embed"
    "io/fs"
    "net/http"
)

//go:embed web/dist
var webfs embed.FS

func main() {
    mux := http.NewServeMux()
    sub, err := fs.Sub(webfs, "web/dist")
    if err != nil {
        panic(err)
    }
    mux.Handle("/", http.FileServer(http.FS(sub)))

    http.ListenAndServe(":2222", mux)
}

When the code is run, I could get the content of index.html through http://127.0.0.1:2222. However, when I changed the line to:

mux.Handle("/admin/", http.FileServer(http.FS(sub)))

I get 404 when accessing http://127.0.0.1:2222/admin/.

CodePudding user response:

You will need to strip the /admin/ off the request path (otherwise the file server will be looking in web/dist/admin). e.g.

mux.Handle("/admin/", http.StripPrefix("/admin/", http.FileServer(http.FS(sub))))

See the docs for StripPrefix for more info.

  •  Tags:  
  • go
  • Related