飞哥的海

导航

Golang: 使用embed内嵌资源文件-转

转载:https://blog.kakkk.net/archives/71/

embed介绍

首先,embed是 go 1.16才有的新特性,使用方法非常简单,通过 //go:embed指令,在打包时将文件内嵌到程序中。

官方文档:https://pkg.go.dev/embed

快速开始

文件结构

.
├── go.mod
├── main.go
└── resources
└── hello.txt

package main

import (
    _ "embed"
    "fmt"
)

//embed指令↓
//go:embed resources/hello.txt
var s string

func main() {
    fmt.Println(s)
}

//输出:
//hello embed!

 

嵌入为字符串

快速开始就是嵌入为字符串的例子,不再多赘述

 

嵌入为byte slice

可以直接以二进制形式嵌入,即嵌入为 byte slice

同样时快速开始里面的文件结构

我们将代码改成如下:

package main

import (
    _ "embed"
    "fmt"
)

//go:embed resources/hello.txt
var b []byte

func main() {
    fmt.Println(string(b[0]))
    fmt.Println(string(b))
}

//输出:
//h
//hello embed!

嵌入为embed.FS

你甚至能嵌入一个文件系统,此时,你能够读取到目录树和文件树,embed.FS对外存在以下方法:

// Open 打开要读取的文件,并返回文件的fs.File结构.
func (f FS) Open(name string) (fs.File, error)

// ReadDir 读取并返回整个命名目录
func (f FS) ReadDir(name string) ([]fs.DirEntry, error)

// ReadFile 读取并返回name文件的内容.
func (f FS) ReadFile(name string) ([]byte, error)

 

映射单个/多个文件

.
├── go.mod
├── main.go
└── resources
    ├── hello1.txt
    └── hello2.txt
package main

import (
    "embed"
    _ "embed"
    "fmt"
)

//go:embed resources/hello1.txt
//go:embed resources/hello2.txt
var f embed.FS

func main() {
    hello1, _ := f.ReadFile("resources/hello1.txt")
    fmt.Println(string(hello1))
    hello2, _ := f.ReadFile("resources/hello2.txt")
    fmt.Println(string(hello2))
}

//输出:
//hello1
//hello2

映射目录

文件结构

.
├── go.mod
├── main.go
└── resources
    ├── dir1
    │   └── dir1.txt
    ├── dir2
    │   ├── dir2.txt
    │   └── dir3
    │       └── dir3.txt
    ├── hello1.txt
    └── hello2.txt
package main

import (
    "embed"
    _ "embed"
    "fmt"
)

//go:embed resources/*
var f embed.FS

func main() {
    hello1, _ := f.ReadFile("resources/hello1.txt")
    fmt.Println(string(hello1))
    hello2, _ := f.ReadFile("resources/hello2.txt")
    fmt.Println(string(hello2))
    dir1, _ := f.ReadFile("resources/dir1/dir1.txt")
    fmt.Println(string(dir1))
    dir2, _ := f.ReadFile("resources/dir2/dir2.txt")
    fmt.Println(string(dir2))
    dir3, _ := f.ReadFile("resources/dir2/dir3/dir3.txt")
    fmt.Println(string(dir3))
}

//输出:
//hello1
//hello2
//dir1
//dir2
//dir3

转载:https://blog.kakkk.net/archives/71/

posted on 2023-08-14 17:55  飞哥的海  阅读(667)  评论(0编辑  收藏  举报