Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

go:embed fs only works for the root with http server?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading