go-embed results in http 404

245 views
Skip to first unread message

Sankar

unread,
Sep 2, 2023, 4:28:11 AM9/2/23
to golang-nuts
I have the following go code where I try to embed a html file from a public directory and running into HTTP 404.  What am I doing wrong ? Relevant code snippet:


// go:embed public
var public embed.FS

func main() {
    // cd to the public directory
    publicFS, err := fs.Sub(public, "public")
    if err != nil {
        log.Fatal(err)
    }
    http.Handle("/embedded/", http.FileServer(http.FS(publicFS)))

    http.Handle("/public/",
        http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))

    log.Fatal(http.ListenAndServe(":8080", nil))
}

The entire golang file and the html file are available in https://github.com/psankar/static-serve

I have tried adding even a `http.StripPrefix` for the `/embedded/` path also but even that does not help. Any pointers on what I am doing wrong ?

Brian Candler

unread,
Sep 2, 2023, 5:36:39 AM9/2/23
to golang-nuts
Firstly, there must be no space between "//" and "go:embed". Otherwise it's just treated as a regular comment, and you get an empty fs with no error.  (Perhaps "go vet" could be enhanced to catch this?)

After fixing this, you'll see the underlying error:
main.go:10:12: pattern public: no matching files found

For an explanation see https://pkg.go.dev/embed#hdr-Directives

"The patterns are interpreted relative to the package directory containing the source file"

These means you'll need to move your public/ directory inside the cmd/ directory. (You can't use a symlink; this causes the embed process to fail with error "cannot embed irregular file")

After that, it should be OK :-)
Reply all
Reply to author
Forward
0 new messages