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. //go:embed image template html/index.html var content embed.FS 区别在于 image/* 会嵌入image/.tempfile 而image 则不会嵌入. 也不会嵌入image/dir/.tempfile.如果要实现跟上面代码一样的效果,即也嵌入image/.tempfile和image/dir/.tempfile这样的文件,那么应该使用下面的这段代码: ...

2022-06-23 · 1 分钟 · 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 != nil { log.Fatal(err) } cmd := exec.Command(path) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { log.Fatal(err) } } You should be able to replace that os.WriteFile with f := os.NewFile(fd, “memfd”); _, err := f.Write(embeddedBinary) for a simpler end result. ...

2022-02-23 · 1 分钟 · czyt