Go Embed Package (Go 1.16+) 🎯

beginner
17 min

Go Embed Package (Go 1.16+) 🎯

Welcome to our deep dive into the Go Embed Package! This tutorial is designed for both beginners and intermediates, so don't worry if you're new to this concept. By the end of this lesson, you'll have a solid understanding of how to use the Go Embed Package to handle files and templates in your Go projects.

What is the Go Embed Package? 📝

The Go Embed Package is a built-in Go package that helps you to embed files or templates in your Go source code. It's incredibly useful for projects that require the use of external files, such as HTML templates, CSS stylesheets, or JSON configuration files.

Why Use the Go Embed Package? 💡

  • Simplifies file management: Instead of manually handling files, the Go Embed Package allows you to include them directly in your Go source code.
  • Easier deployment: Including files in your Go source code makes it simpler to deploy your application as a single binary.
  • Flexible: The Go Embed Package supports various file formats, including HTML, CSS, JSON, and more.

Getting Started 📝

To use the Go Embed Package, you first need to import it in your Go source file:

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

Now, let's create a function to load an embedded file:

go
func loadFile(name string) (fs.File, error) { // Embed the files var fs embedding.FS // Use the EmbedFS method to embed the files fs = embedding.EmbedFS(fs, map[string]string{ "index.html": `<html> <body> <h1>Hello, Go Embed!</h1> </body> </html>`, }) // Use the Open method to open the embedded file return fs.Open(name) }

In the above example, we've embedded an HTML file named index.html directly in our Go source code.

Using Embedded Files 💡

Now that we've embedded our file, we can use it in our Go application:

go
func main() { // Load the embedded file file, err := loadFile("index.html") if err != nil { log.Fatal(err) } // Read the embedded file io.Copy(os.Stdout, file) }

When you run this Go program, it will print the embedded HTML file to the console:

$ go run main.go <html> <body> <h1>Hello, Go Embed!</h1> </body> </html>

Embedding Multiple Files 📝

You can embed multiple files by extending the EmbedFS function:

go
func loadFS() embedding.FS { return embedding.EmbedFS( embedding.FS{ "index.html": `<html> <body> <h1>Hello, Go Embed!</h1> </body> </html>`, }, embedding.FS{ "styles.css": `body { color: blue; }`, }, ) }

Using Embedded Files with Templates 💡

You can also use the Go Embed Package with template packages like html/template to create dynamic HTML pages:

go
func main() { // Load the embedded files templateFS := loadFS() t, err := template.ParseFS(templateFS, "index.html") if err != nil { log.Fatal(err) } // Create a data structure for our data data := map[string]string{ "Title": "Go Embed and Templates", } // Execute the template with our data err = t.Execute(os.Stdout, data) if err != nil { log.Fatal(err) } }

In this example, we've loaded an HTML template and executed it with some data. The resulting HTML will have the title "Go Embed and Templates".

Challenge: Embed a JSON Configuration File 🎯

Embed a JSON configuration file named config.json and read it in your Go program:

go
func loadConfig() (map[string]interface{}, error) { // Embed the files var fs embedding.FS // Use the EmbedFS method to embed the files fs = embedding.EmbedFS(fs, map[string]string{ "config.json": `{ "title": "Go Embed and JSON", "author": "CodeYourCraft" }`, }) // Use the ReadFile method to read the embedded JSON file data, err := fs.ReadFile("config.json") if err != nil { return nil, err } // Use the json.Unmarshal function to parse the JSON data var config map[string]interface{} err = json.Unmarshal(data, &config) if err != nil { return nil, err } return config, nil }

Now, you can use the loadConfig function to read the embedded JSON configuration file in your Go program.

Quick Quiz
Question 1 of 1

What is the Go Embed Package used for?