다른 사람이 구성 파일을 수정하지 못하도록 go-bindata를 사용하여 구성 파일을 실행 가능한 프로그램으로 패키징합니다.

 

일반적으로 백엔드 서비스를 시작하려면 구성 파일이 필요하지만 구성 파일에는 민감한 정보가 포함되어 있으므로 보안상의 이유로 구성 파일을 직접 실행 파일로 컴파일합니다. .toml, .json, .yaml 및 기타 접미사가 붙은 파일을 패키징할 수 있는데 저는 .toml을 사용합니다. 비즈니스 요구사항에 따라 선택하세요. 원칙은 동일합니다.

단계:

1. go-bindata 패키지 설치

가서 -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 파일 내용 예시
[일반적인]
듣기="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    string `mapstructure:"listen"`
	}`mapstructure:"general"`
}

func conf(b []byte) {
	if len(b) >= 0  {
		viper.SetConfigType("toml")
		if err := viper.ReadConfig(bytes.NewBuffer(b)); err != nil {
			fmt.Println("error loading config file")
		}
	}

	if err := viper.Unmarshal(&C); err != nil {
		fmt.Println("error loading config file",err)
	}
}

5. 생성된 conf.go 파일도 직접 올려드리겠습니다.

package main

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"strings"
)

func bindata_read(data []byte, name string) ([]byte, error) {
	gz, err := gzip.NewReader(bytes.NewBuffer(data))
	if err != nil {
		return nil, fmt.Errorf("Read %q: %v", name, err)
	}

	var buf bytes.Buffer
	_, err = io.Copy(&buf, gz)
	gz.Close()

	if err != nil {
		return nil, fmt.Errorf("Read %q: %v", name, err)
	}

	return buf.Bytes(), nil
}

var _test_toml = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x8a\x4e\x4f\xcd\x4b\x2d\x4a\xcc\x89\xe5\xe5\xca\xc9\x2c\x2e\x49\xcd\xb3\x55\x32\xd0\x03\x43\x2b\x4b\x03\x4b\x03\x25\x40\x00\x00\x00\xff\xff\x62\x15\x90\x2b\x20\x00\x00\x00")

func test_toml() ([]byte, error) {
	return bindata_read(
		_test_toml,
		"test.toml",
	)
}

// Asset loads and returns the asset for the given name.
// It returns an error if the asset could not be found or
// could not be loaded.
func Asset(name string) ([]byte, error) {
	cannonicalName := strings.Replace(name, "\\", "/", -1)
	if f, ok := _bindata[cannonicalName]; ok {
		return f()
	}
	return nil, fmt.Errorf("Asset %s not found", name)
}

// AssetNames returns the names of the assets.
func AssetNames() []string {
	names := make([]string, 0, len(_bindata))
	for name := range _bindata {
		names = append(names, name)
	}
	return names
}

// _bindata is a table, holding each asset generator, mapped to its name.
var _bindata = map[string]func() ([]byte, error){
	"test.toml": test_toml,
}
// AssetDir returns the file names below a certain
// directory embedded in the file by go-bindata.
// For example if you run go-bindata on data/... and data contains the
// following hierarchy:
//     data/
//       foo.txt
//       img/
//         a.png
//         b.png
// then AssetDir("data") would return []string{"foo.txt", "img"}
// AssetDir("data/img") would return []string{"a.png", "b.png"}
// AssetDir("foo.txt") and AssetDir("notexist") would return an error
// AssetDir("") will return []string{"data"}.
func AssetDir(name string) ([]string, error) {
	node := _bintree
	if len(name) != 0 {
		cannonicalName := strings.Replace(name, "\\", "/", -1)
		pathList := strings.Split(cannonicalName, "/")
		for _, p := range pathList {
			node = node.Children[p]
			if node == nil {
				return nil, fmt.Errorf("Asset %s not found", name)
			}
		}
	}
	if node.Func != nil {
		return nil, fmt.Errorf("Asset %s not found", name)
	}
	rv := make([]string, 0, len(node.Children))
	for name := range node.Children {
		rv = append(rv, name)
	}
	return rv, nil
}

type _bintree_t struct {
	Func func() ([]byte, error)
	Children map[string]*_bintree_t
}
var _bintree = &_bintree_t{nil, map[string]*_bintree_t{
	"test.toml": &_bintree_t{test_toml, map[string]*_bintree_t{
	}},
}}

Je suppose que tu aimes

Origine blog.csdn.net/xia_2017/article/details/122084375
conseillé
Classement