go基础学习-yaml文件的解析
YAML 是一种简洁的非标记语言。YAML以数据为中心,使用空白,缩进,分行组织数据,从而使得表示更加简洁易读。
1.创建config.yaml
内容如下:
1 2 3 4 5 6 7 | app: api env: dev https: true nginx: port: 443 logPath: "/var/log//nginx/nginx.log" path: "/opt/nginx/" |
2.创建config/config.go
内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import ( "fmt" "gopkg.in/yaml.v2" "io/ioutil" "montitor/global" ) func GetConfig() { config, err := ioutil.ReadFile( "config.yaml" ) ##读取yaml文件信息 if err != nil { fmt.Print(err) } yaml.Unmarshal(config, &global.CONFIG) } |
3.创建global/global.go
内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package global //Nginx nginx 配置 type Nginx struct { Port int `yaml: "port" ` LogPath string `yaml: "logPath" ` Path string `yaml: "path" ` } //Config 系统配置配置 type Config struct { Env string `yaml: "env" ` App string `yaml: "app" ` SiteNginx Nginx `yaml: "nginx" ` }<br> ###全局变量 var ( CONFIG = new(Config) ) |
4.main.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package main import ( "fmt" "montitor/config" "montitor/global" ) func main() { config.GetConfig() fmt.Println(global.CONFIG.Env) fmt.Println(global.CONFIG.App) fmt.Println(global.CONFIG.SiteNginx.Port) fmt.Println(global.CONFIG.SiteNginx.LogPath) fmt.Println(global.CONFIG.SiteNginx.Path) } |
5.go run main.go
dev
api
443
/var/log//nginx/nginx.log
/opt/nginx/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具