通常后端服务启动需要的配置文件,然而配置文件中包含了敏感信息,出于安全考虑,将配置文件直接编译到可以执行文件中。.toml,.json,.yaml等后缀的文件都可以打包,我使用的是.toml。根据业务需要来选择。原理都一样
操作步骤:
1. 安装go-bindata包
go get -u github.com/go-bindata/go-bindata/...
2. 查看是否安装成功
执行: go-bindata -help,出现如图,表示安装成功

3. 执行编译语句
go-bindata -pkg=tool -o=./tool/conf.go test.toml
-pkg : 表示目录名,目录名不存在会自动创建在当前目录下
-o:表示将配置文件生成的.go文件放到那个目录的那个文件下
test.toml: 要打包的配置文件
4. 代码示例,使用的配置文件如下
# test.toml文件内容示例 [general] listen="0.0.0.0:9090"
package main
import (
"bytes"
"fmt"
"github.com/spf13/viper"
)
func main(){
data, _ := Asset("test.toml")
fmt.Println(string(data))
conf(data)
fmt.Println("listen:",C.General.Listen)
}
var C Config
type Config struct {
General struct {
Listen

本文介绍了一种将敏感配置文件编译进可执行文件的方法,通过go-bindata工具实现,并提供了详细的操作步骤与代码示例。
最低0.47元/天 解锁文章
5032





