Home > Backend Development > Golang > How Can I Embed Files into Go Binaries Using `go:embed` and `go generate`?

How Can I Embed Files into Go Binaries Using `go:embed` and `go generate`?

Susan Sarandon
Release: 2024-12-18 02:32:10
Original
366 people have browsed it

How Can I Embed Files into Go Binaries Using `go:embed` and `go generate`?

Embedding Files into Go Binaries

In programming, it is common to distribute executable files that require additional resources, such as text files. To simplify deployment and avoid having to distribute multiple files, it is beneficial to embed these resources within the binary itself.

Embedding Files with go:embed (Go 1.16 and later)

With Go 1.16, the go:embed directive provides a straightforward method for embedding files:

package main

import "embed"

// Embed the "hello.txt" file as a string
//go:embed hello.txt
var s string

// Embed the "hello.txt" file as a byte slice
//go:embed hello.txt
var b []byte

// Embed the "hello.txt" file as an embed.FS object
//go:embed hello.txt
var f embed.FS

func main() {
    // Read the file contents as a string
    data, _ := f.ReadFile("hello.txt")
    println(string(data))
}
Copy after login

Embedding Files with go generate (Before Go 1.16)

For earlier versions of Go, go generate offers an alternative approach:

  1. Create an includetxt.go script: This script will read the text files and generate string literals for them.
  2. Add the go:generate comment to main.go: The comment will trigger the execution of the includetxt.go script and generate the string literals.
  3. Example code:

    main.go

    package main
    
    import "fmt"
    
    //go:generate go run scripts/includetxt.go
    
    func main() {
        fmt.Println(a)
        fmt.Println(b)
    }
    Copy after login

    scripts/includetxt.go

    package main
    
    import (
        "io"
        "io/ioutil"
        "os"
        "strings"
    )
    
    // Embed all .txt files as string literals
    func main() {
        fs, _ := ioutil.ReadDir(".")
        out, _ := os.Create("textfiles.go")
    
        for _, f := range fs {
            if strings.HasSuffix(f.Name(), ".txt") {
                out.WriteString(strings.TrimSuffix(f.Name(), ".txt") + " = `")
                f, _ := os.Open(f.Name())
                io.Copy(out, f)
                out.WriteString("`\n")
            }
        }
    }
    Copy after login
  4. Compilation:

    $ go generate
    $ go build -o main
    Copy after login

Additional Notes:

  • The go generate approach requires the text files to be UTF-8 encoded.
  • For non-UTF-8 files, you can use custom encoding in the includetxt.go script.
  • The embed.FS type in go:embed provides access to the embedded files using a virtual file system.

The above is the detailed content of How Can I Embed Files into Go Binaries Using `go:embed` and `go generate`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template