go embed 使用小记

​ go embed 是go 1.16 开始添加的特性,允许嵌入文件及文件夹,在Go程序中进行使用。官方还为此添加了embed.FS的对象。下面将常用的使用场景进行简单列举: 嵌入单个文件 官方的例子 嵌入文件并绑定到字符串变量 import _ "embed" //go:embed hello.txt var s string print(s) 嵌入文件并绑定到字节变量 import _ "embed" //go:embed hello.txt var b []byte print(string(b)) 嵌入文件并绑定到文件对象 import "embed" //go:embed hello.txt var f embed.FS data, _ := f.ReadFile("hello.txt") print(string(data)) 嵌入目录 嵌入时,可以在多行或者一行输入要嵌入的文件和文件夹。 package server import "embed" // content holds our static web server content. //go:embed image/* template/* //go:embed html/index.html var content embed.FS 在匹配文件夹时,embed会嵌入包括子目录下的所有除.和_开头的文件(递归),所以上面的代码大致等价于下面的代码: // content is our static web server content....

June 23, 2022 · 1 min · czyt

Golang嵌入可执行程序

reddit链接 On Linux it might be possible to use the memfd_create system call, but that’s not portable to other operating systems. need go 1.16 + package main import ( _ "embed" "log" "os" "os/exec" "strconv" "golang.org/x/sys/unix" ) //go:embed binary var embeddedBinary []byte func main() { fd, err := unix.MemfdCreate("embedded_binary", 0) if err != nil { log.Fatal(err) } path := "/proc/" + strconv.Itoa(os.Getpid()) + "/fd/" + strconv.Itoa(int(fd)) err = os.WriteFile(path, embeddedBinary, 0755) if err !...

February 23, 2022 · 1 min · czyt