Foreword
viper는 Yaml, Json, TOML, HCL 및 기타 형식을 지원하므로 읽기가 매우 편리합니다.
Install
go get github.com/spf13/viper
프롬프트에서 golang.org/x/text/ 라이브러리를 찾을 수 없다면 이는 golang.org/x/text 때문입니다. / 이 라이브러리가 GitHub에서 호스팅되는 경로가 일치하지 않습니다.
해결책:
https://github.com/golang/text에서 소스 코드를 다운로드한 다음 $GOPATH/src 아래에 golang.org/x/ 폴더를 만들 수 있습니다(기존 폴더는 무시). ) , golang.org/x/ 폴더에 압축 파일을 추출합니다. + | 각 콜론 뒤에는 공백이 있어야 하며 연속성을 나타내기 위해 배열 앞에 "-" 기호를 추가해야 합니다. 빼기 기호 뒤의 공백) 내용은 다음과 같습니다.
TimeStamp: "2018-10-18 10:09:23" Address: "Shenzhen" Postcode: 518000 CompanyInfomation: Name: "Sunny" MarketCapitalization: 50000000 EmployeeNum: 200 Department: - "Finance" - "Design" - "Program" - "Sales" IsOpen: false
yaml 파일 읽기:
package main import ( "github.com/spf13/viper" "fmt" ) func main() { //读取yaml文件 v := viper.New() //设置读取的配置文件 v.SetConfigName("linux_config") //添加读取的配置文件路径 v.AddConfigPath("./config/") //windows环境下为%GOPATH,linux环境下为$GOPATH v.AddConfigPath("$GOPATH/src/") //设置配置文件类型 v.SetConfigType("yaml") if err := v.ReadInConfig();err != nil { fmt.Printf("err:%s\n",err) } fmt.Printf( ` TimeStamp:%s CompanyInfomation.Name:%s CompanyInfomation.Department:%s `, v.Get("TimeStamp"), v.Get("CompanyInfomation.Name"), v.Get("CompanyInfomation.Department"), ) /* result: TimeStamp:2018-10-18 10:09:23 CompanyInfomation.Name:Sunny CompanyInfomation.Department:[Finance Design Program Sales] */ }
또한 Struct로 직렬화하는 것을 직접 역방향으로 수행하는 것이 매우 편리합니다. package main
import (
"github.com/spf13/viper"
"fmt"
)
func main() {
//读取yaml文件
v := viper.New()
//设置读取的配置文件
v.SetConfigName("linux_config")
//添加读取的配置文件路径
v.AddConfigPath("./config/")
//windows环境下为%GOPATH,linux环境下为$GOPATH
v.AddConfigPath("$GOPATH/src/")
//设置配置文件类型
v.SetConfigType("yaml")
if err := v.ReadInConfig();err != nil {
fmt.Printf("err:%s\n",err)
}
fmt.Printf(
`
TimeStamp:%s
CompanyInfomation.Name:%s
CompanyInfomation.Department:%s `,
v.Get("TimeStamp"),
v.Get("CompanyInfomation.Name"),
v.Get("CompanyInfomation.Department"),
)
/*
result:
TimeStamp:2018-10-18 10:09:23
CompanyInfomation.Name:Sunny
CompanyInfomation.Department:[Finance Design Program Sales]
*/
//反序列化
parseYaml(v)
}
type CompanyInfomation struct{
Name string
MarketCapitalization int64
EmployeeNum int64
Department []interface{}
IsOpen bool
}
type YamlSetting struct{
TimeStamp string
Address string
Postcode int64
CompanyInfomation CompanyInfomation
}
func parseYaml(v *viper.Viper){
var yamlObj YamlSetting;
if err := v.Unmarshal(&yamlObj) ; err != nil{
fmt.Printf("err:%s",err)
}
fmt.Println(yamlObj)
/*
result:
{2018-10-18 10:09:23 Shenzhen 518000 {Sunny 50000000 200 [Finance Design Program Sales] false}}
*/
}
Viper는 명령줄 매개변수를 읽는 기능도 제공합니다. : package main
import (
"github.com/spf13/pflag"
"github.com/spf13/viper"
"fmt"
)
func main() {
pflag.String("hostAddress", "127.0.0.1", "Server running address")
pflag.Int64("port", 8080, "Server running port")
pflag.Parse()
viper.BindPFlags(pflag.CommandLine)
fmt.Printf("hostAddress :%s , port:%s", viper.GetString("hostAddress"), viper.GetString("port"))
/*
example:
go run main2.go --hostAddress=192.192.1.10 --port=9000
help:
Usage of /tmp/go-build183981952/b001/exe/main:
--hostAddress string Server running address (default "127.0.0.1")
--port int Server running port (default 8080)
*/
}
서버가 시작된 후 일부 구성 매개변수를 일시적으로 수정하려면 서버를 다시 시작해야 적용되는 경우가 많습니다. 하지만 viper는 다시 시작하지 않고도 구성 매개변수를 수정할 수 있는 수신 기능을 제공합니다. 매우 실용적입니다.
package main import ( "github.com/spf13/viper" "fmt" "golang.org/x/net/context" "github.com/fsnotify/fsnotify" ) func main() { //读取yaml文件 v := viper.New() //设置读取的配置文件 v.SetConfigName("linux_config") //添加读取的配置文件路径 v.AddConfigPath("./config/") //windows环境下为%GOPATH,linux环境下为$GOPATH v.AddConfigPath("$GOPATH/src/") //设置配置文件类型 v.SetConfigType("yaml") if err := v.ReadInConfig(); err != nil { fmt.Printf("err:%s\n", err) } //创建一个信道等待关闭(模拟服务器环境) ctx, _ := context.WithCancel(context.Background()) //cancel可以关闭信道 //ctx, cancel := context.WithCancel(context.Background()) //设置监听回调函数 v.OnConfigChange(func(e fsnotify.Event) { fmt.Printf("config is change :%s \n", e.String()) //cancel() }) //开始监听 v.WatchConfig() //信道不会主动关闭,可以主动调用cancel关闭 <-ctx.Done() /* result: config is change :"/home/share/go/Viper/config/linux_config.yaml": CREATE config is change :"/home/share/go/Viper/config/linux_config.yaml": CREATE */ }End
위 내용은 Golang에서 유용한 바이퍼 구성 모듈을 공유하세요의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

goisidealforbuildingscalablesystemsduetoitssimplicity, 효율성 및 빌드-내부 컨 컨 오렌 스upport.1) go'scleansyntaxandminimalisticdesignenenhance-reductivityandreduceerrors.2) itsgoroutinesandChannelsableefficedsoncurrentProgramming, DistributingLoa

initTectionsIntOnaUtomaticallyBeforemain () andAreSefulforsettingupenvirondentAnitializingVariables.usethemforsimpletasks, propoysideeffects 및 withtestingntestingandloggingtomaincodeclarityAndestability.

goinitializespackages는 theyareimported, theexecutesinitfunctions, theneiredefinitionorder, andfilenamesDeterMineDeTerMineTeRacrossMultipleFiles.ThemayLeadTocomplexInitializations의 의존성 의존성의 의존성을 확인합니다

CustomInterfacesingoAreCrucialForwritingFlectible, 관리 가능 및 TestAblEcode.theyenabledeveloperstofocusonBehaviorimplementation, 향상 ModularityAndRobustness

시뮬레이션 및 테스트에 인터페이스를 사용하는 이유는 인터페이스가 구현을 지정하지 않고 계약의 정의를 허용하여 테스트를보다 고립되고 유지 관리하기 쉽기 때문입니다. 1) 인터페이스를 암시 적으로 구현하면 테스트에서 실제 구현을 대체 할 수있는 모의 개체를 간단하게 만들 수 있습니다. 2) 인터페이스를 사용하면 단위 테스트에서 서비스의 실제 구현을 쉽게 대체하여 테스트 복잡성과 시간을 줄일 수 있습니다. 3) 인터페이스가 제공하는 유연성은 다른 테스트 사례에 대한 시뮬레이션 동작의 변화를 허용합니다. 4) 인터페이스는 처음부터 테스트 가능한 코드를 설계하여 코드의 모듈성과 유지 관리를 향상시키는 데 도움이됩니다.

GO에서는 INT 기능이 패키지 초기화에 사용됩니다. 1) INT 기능은 패키지 초기화시 자동으로 호출되며 글로벌 변수 초기화, 연결 설정 및 구성 파일로드에 적합합니다. 2) 파일 순서로 실행할 수있는 여러 개의 초기 함수가있을 수 있습니다. 3)이를 사용할 때 실행 순서, 테스트 난이도 및 성능 영향을 고려해야합니다. 4) 부작용을 줄이고, 종속성 주입을 사용하고, 초기화를 지연하여 초기 기능의 사용을 최적화하는 것이 좋습니다.

go'selectStatementsTreamLinesconcurramprogrammingBymultiplexingOperations.1) ItallowSwaitingOnMultipLechannelOperations, executingThefirStreadYone.2) thedefaultCasePreventsDeadLocksHavingThepRamToproCeedifNooperationSready.3) Itcanusedfored

Contextandwaitgroupsarecrucialingformaninggoroutineeseforoutineeseferfectial


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.
