Home > Backend Development > Golang > How Can I Embed Files into My Go Binaries?

How Can I Embed Files into My Go Binaries?

Linda Hamilton
Release: 2024-12-31 21:17:13
Original
814 people have browsed it

How Can I Embed Files into My Go Binaries?

Incorporating Files into Go Binaries

Want to distribute a single executable that includes necessary text files? Go provides solutions for embedding files into binaries, tailored for various platforms.

Go 1.16 and Beyond: go:embed Directive

For Go versions 1.16 and higher, leverage the go:embed directive. It offers an elegant way to embed files:

import "embed"

//go:embed hello.txt
var s string
print(s)

//go:embed hello.txt
var b []byte
print(string(b))

//go:embed hello.txt
var f embed.FS
data, _ := f.ReadFile("hello.txt")
print(string(data))
Copy after login

Go 1.4 and Later: go generate for Flexibility

For Go versions 1.4 and onward, you can resort to go generate for greater flexibility. This approach involves:

  1. Creating a go script that reads text files and generates string literals.
  2. Using a go:generate comment in your main file to invoke the script.

This technique enables embedding multiple text files with minimal hardcoding. For instance:

main.go

package main

import "fmt"

//go:generate go run scripts/includetxt.go

func main() {
    fmt.Println(a)
    fmt.Println(b)
}
Copy after login

script/includetxt.go

package main

import (
    "io"
    "io/ioutil"
    "os"
    "strings"
)

func main() {
    fs, _ := ioutil.ReadDir(".")
    out, _ := os.Create("textfiles.go")
    out.Write([]byte("package main \n\nconst (\n"))
    for _, f := range fs {
        if strings.HasSuffix(f.Name(), ".txt") {
            out.Write([]byte(strings.TrimSuffix(f.Name(), ".txt") + " = `"))
            f, _ := os.Open(f.Name())
            io.Copy(out, f)
            out.Write([]byte("`\n"))
        }
    }
    out.Write([]byte(")\n"))
}
Copy after login

Build Commands:

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

The above is the detailed content of How Can I Embed Files into My Go Binaries?. 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