golang的go:embed的使用注意事项

       golang嵌入静态文件的方式很多,但是1.16版开始官方也出台了方案。自带了go:embed标签来完成,但是在使用时会有很多的不方便,我们来看一下。

        1、文件不是utf8编码时,输出内容为中文会乱码。

        2、嵌入文件只能为源码文件同级目录和子目录下的文件。

        尤其是第2项是很不方便的,一般的静态文件会单独放在根及目录下,而嵌入的文件则可能在其它目录里。

package main
 
import (
  _ "embed"
)
 
//go:embed test1.txt
var testString string // 当前目录,解析为string类型
 
//go:embed test2.txt
var testByte []byte // 当前目录,解析为[]byte类型
 
//go:embed test/test3.txt
var testAbsolutePath string // 子目录,解析为string类型
 
//go:embed notExistsFile
var testErr0 string // 文件不存在,编译报错:pattern notExistsFile: no matching files found
 
//go:embed dir
var testErr1 string // dir是目录,编译报错:pattern dir: cannot embed directory dir: contains no embeddable files
 
//go:embed ../test.txt
var testErr2 string // 相对路径,不是当前目录或子目录,编译报错:pattern ../test.txt: invalid pattern syntax
 
//go:embed /User/test.txt
var testErr3 string // 绝对路径,编译报错:pattern /User/test.txt: no matching files found
 
func main() {
  println(testString)
  println(string(testByte))
  println(testAbsolutePath)
}

猜你喜欢

转载自blog.csdn.net/saperliu/article/details/126535810