The embed package in Go (Golang) provides a way to embed static files directly into your executable, making it easier to distribute and deploy applications. This feature is particularly useful for including configuration files, templates, images, or any other static assets without the need for external dependencies.
Before diving into how to use the embed package, let's understand its purpose and benefits:
To use the embed package, you first need to import it:
import "embed"
Here's how you can embed a single file:
//go:embed hello.txt
var helloFile string
In this example, hello.txt is embedded into the variable helloFile. The content of hello.txt will be stored as a string in helloFile.
To embed multiple files, you can use a slice:
//go:embed hello.txt world.txt
var files []string
This will store the contents of both hello.txt and world.txt in the files slice.
You can also embed entire directories using the embed.FS type:
//go:embed assets/*
var assetFS embed.FS
In this case, all files within the assets directory will be embedded into assetFS.
To read the content of an embedded file, you can use the strings package:
package main
import (
"fmt"
"strings"
_ "embed"
)
//go:embed hello.txt
var helloFile string
func main() {
fmt.Println(strings.TrimSpace(helloFile))
}
For multiple files, you can iterate over the slice and read each file:
package main
import (
"fmt"
"strings"
_ "embed"
)
//go:embed hello.txt world.txt
var files []string
func main() {
for _, file := range files {
fmt.Println(strings.TrimSpace(file))
}
}
To read files from an embedded directory, use the embed.FS type:
package main
import (
"embed"
"fmt"
"io/fs"
)
//go:embed assets/*
var assetFS embed.FS
func main() {
dirEntries, _ := fs.ReadDir(assetFS, "assets")
for _, entry := range dirEntries {
if !entry.IsDir() {
fileContent, _ := fs.ReadFile(assetFS, entry.Name())
fmt.Println(string(fileContent))
}
}
}
Let's create a simple web server that serves static HTML content from an embedded directory:
package main
import (
"embed"
"fmt"
"net/http"
_ "embed"
)
//go:embed templates/*
var templateFS embed.FS
func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(templateFS))))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "templates/index.html")
})
fmt.Println("Starting server at port 8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Printf("Failed to start server: %v\n", err)
}
}
In this example:
templates directory is embedded into the application.index.html file.The embed package in Go provides a powerful and flexible way to include static files directly into your executable. By following best practices and understanding how to access and use embedded files, you can streamline your application's deployment and management process.