Golang
主页 > 脚本 > Golang >

Golang嵌入资源文件实现步骤

2023-01-11 | 佚名 | 点击:

Go文档中展示了多种方式实现外部资源嵌入,包括文本文件、图片、ios文件等:

文本文件

1

2

3

4

5

6

7

package main

import _ "embed"

//go:embed schema.sql

var tableCreate string

func main() {

    print(tableCreate)

}

在构建时,schema.sql内容会嵌入至应用中,使得tableCreate字符串变量可用。与通过环境变量嵌入信息至应用类似。

输出结果:

1

2

3

4

5

create table sys_user(

    id int,

    name varchar(36),

    birth date

)

图片文件

如果是图片,可以编码为二进制字节切片:

1

2

3

4

5

6

7

8

9

10

package main

import (

    _ "embed"

    "encoding/base64"

)

//go:embed logo.png

var logo []byte

func main() {

    print(base64.RawStdEncoding.EncodeToString(logo))

}

镜像文件

一旦在内存中,logo文件就可以通过HTTP连接提供给客户端使用。使用embed.FS接口与上面示例不同,数据仅当需要时才会加载至内存,这种方法对于大文件非常有用:

1

2

3

4

5

6

7

8

9

10

11

package main

import (

    "embed"

    "fmt"

)

//go:embed ubuntu-20-cloud.iso

var f embed.FS

func main() {

    data, _ := f.ReadFile("ubuntu-20-cloud.iso")

    fmt.Printf("Total bytes: %d\n", len(data))

}

Go是一种非常好的系统编程语言,它提供了许多用于管理文件系统和网络的包,应用可能会在程序中发送类似ISO映像文件,可以随时将其写入磁盘中。

前端应用文件

有时希望把前端应用的文件嵌入至应用中,和http服务一起实现完整web应用。

// frontend holds our static web server content.
//go:embed image/* template/*
//go:embed public/index.html
//go:embed css/*

var frontend embed.FS

现在可以简单连接embed.FS至自定义HTTP中间件或处理器,从特点路由或路径给用户提供文件。下面时Go文档中提供的示例:

http.Handle( "/public/",
    http.StripPrefix( "/public/",
        http.FileServer( http.FS(frontend))))

你的API可以被绑定到路径/API/v1/,然后你嵌入的任何静态内容都会通过/public/路由提供访问。

编译打包

go build .

通过编译打包,会生成独立可执行文件。拷贝至任何目录也可以直接运行,不会因为找不到资源文件而报错。

原文链接:https://blog.csdn.net/neweastsun/article/details/128437948
相关文章
最新更新