Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: embed static files in binary

Tags:

go

This might be a very amateur question. I'm trying to embed static files into binary, ie. html. How do I do that with https://github.com/jteeuwen/go-bindata?

So I can access an asset with this https://github.com/jteeuwen/go-bindata#accessing-an-asset, but what do I do with "data", and how to do I parse files, execute template, and serve them in the directory?

I couldn't find any examples online, and will appreciate some help!

like image 552
user3918985 Avatar asked Dec 14 '22 17:12

user3918985


1 Answers

5/6 years later, this should be easier with Go 1.16 (Q1 2021), which adds support for embedded files (issue/proposal 41191 )

It will be permitted to use //go:embed naming a single file to initialize a plain string or []byte variable:

//go:embed gopher.png
var gopherPNG []byte

The import is required to flag the file as containing //go:embed lines and needing processing.
Goimports (and gopls etc) can be taught this rule and automatically add the import in any file with a //go:embed as needed.

That sparked a debate on issue 42328 about how to avoid surprising inclusion of "hidden" files when using //go:embed

This as resolved in CL 275092 and commit 37588ff

Decision to exclude files matching .* and _* from embedded directory results when embedding an entire directory tree.

See src/embed/internal/embedtest/embed_test.go

    //go:embed testdata/k*.txt
    var local embed.FS
    testFiles(t, local, "testdata/ken.txt", "If a program is too slow, it must have a loop.\n")

    //go:embed testdata/k*.txt
    var s string
    testString(t, s, "local variable s", "If a program is too slow, it must have a loop.\n")

    //go:embed testdata/h*.txt
    var b []byte
    testString(t, string(b), "local variable b", "hello, world\n")

Note: with CL 281492, cmd/go passes embedcfg to gccgo if supported.


See also (Jan. 2021) issue 43854 "opt-in for //go:embed to not ignore files and empty dirs".

like image 62
VonC Avatar answered May 06 '23 06:05

VonC