go toml example

矫情吗;* 2023-02-17 05:04 80阅读 0赞

github 官方地址

官方例子:

  1. // example.go
  2. package main
  3. import (
  4. "fmt"
  5. "time"
  6. "github.com/BurntSushi/toml"
  7. )
  8. type tomlConfig struct {
  9. Title string
  10. Owner ownerInfo
  11. DB database `toml:"database"`
  12. Servers map[string]server
  13. Clients clients
  14. }
  15. type ownerInfo struct {
  16. Name string
  17. Org string `toml:"organization"`
  18. Bio string
  19. DOB time.Time
  20. }
  21. type database struct {
  22. Server string
  23. Ports []int
  24. ConnMax int `toml:"connection_max"`
  25. Enabled bool
  26. }
  27. type server struct {
  28. IP string
  29. DC string
  30. }
  31. type clients struct {
  32. Data [][]interface{}
  33. Hosts []string
  34. }
  35. func main() {
  36. var config tomlConfig
  37. if _, err := toml.DecodeFile("example.toml", &config); err != nil {
  38. fmt.Println(err)
  39. return
  40. }
  41. fmt.Printf("Title: %s\n", config.Title)
  42. fmt.Printf("Owner: %s (%s, %s), Born: %s\n",
  43. config.Owner.Name, config.Owner.Org, config.Owner.Bio,
  44. config.Owner.DOB)
  45. fmt.Printf("Database: %s %v (Max conn. %d), Enabled? %v\n",
  46. config.DB.Server, config.DB.Ports, config.DB.ConnMax,
  47. config.DB.Enabled)
  48. for serverName, server := range config.Servers {
  49. fmt.Printf("Server: %s (%s, %s)\n", serverName, server.IP, server.DC)
  50. }
  51. fmt.Printf("Client data: %v\n", config.Clients.Data)
  52. fmt.Printf("Client hosts: %v\n", config.Clients.Hosts)
  53. }
  54. # example.toml
  55. # This is a TOML document. Boom.
  56. title = "TOML Example"
  57. [owner]
  58. name = "Tom Preston-Werner"
  59. organization = "GitHub"
  60. bio = "GitHub Cofounder & CEO\nLikes tater tots and beer."
  61. dob = 1979-05-27T07:32:00Z # First class dates? Why not?
  62. [database]
  63. server = "192.168.1.1"
  64. ports = [ 8001, 8001, 8002 ]
  65. connection_max = 5000
  66. enabled = true
  67. [servers]
  68. # You can indent as you please. Tabs or spaces. TOML don't care.
  69. [servers.alpha]
  70. ip = "10.0.0.1"
  71. dc = "eqdc10"
  72. [servers.beta]
  73. ip = "10.0.0.2"
  74. dc = "eqdc10"
  75. [clients]
  76. data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it
  77. # Line breaks are OK when inside arrays
  78. hosts = [
  79. "alpha",
  80. "omega"
  81. ]

发表评论

表情:
评论列表 (有 0 条评论,80人围观)

还没有评论,来说两句吧...

相关阅读

    相关 TOML基本介绍

    GitHub 目前的新项目已经转用 [CoffeeScript][] 了。CoffeeScript 比 JavaScript 要简洁优雅得多。同样地,GitHub 也觉得 YA