Leggere file TOML in Go

Mattepuffo's logo
Leggere file TOML in Go

Leggere file TOML in Go

In questo articolo vediamo come leggere un file TOML in Go.

Useremo la libreria useremo BurntSushi/toml.

Per installarla:

go get github.com/BurntSushi/toml

Questo il file TOML:

title = "Test TOML"
version = "1.0.0"

[database]
host = "localhost"
port = 5432
username = "root"
password = "password"
databases = ["db_test"]
pool_size = 10
ssl_enabled = true

[server]
host = "0.0.0.0"
port = 8080
debug = false
allowed_hosts = ["*"]

[logging]
level = "INFO"
format = "%(asctime)s - %(levelname)s - %(message)s"
handlers = ["console", "file"]

[cache]
enabled = true
ttl = 3600
max_size = 1000

[features]
enable_api = true
rate_limit = 100

Qui sotto un pò di codice:

package main

import (
	"fmt"
	"log"

	"github.com/BurntSushi/toml"
)

type Config struct {
	Title    string   `toml:"title"`
	Version  string   `toml:"version"`
	Database Database `toml:"database"`
	Server   Server   `toml:"server"`
	Logging  Logging  `toml:"logging"`
	Cache    Cache    `toml:"cache"`
	Features Features `toml:"features"`
}

type Database struct {
	Host       string   `toml:"host"`
	Port       int      `toml:"port"`
	Username   string   `toml:"username"`
	Password   string   `toml:"password"`
	Databases  []string `toml:"databases"`
	PoolSize   int      `toml:"pool_size"`
	SSLEnabled bool     `toml:"ssl_enabled"`
}

type Server struct {
	Host         string   `toml:"host"`
	Port         int      `toml:"port"`
	Debug        bool     `toml:"debug"`
	AllowedHosts []string `toml:"allowed_hosts"`
}

type Logging struct {
	Level    string   `toml:"level"`
	Format   string   `toml:"format"`
	Handlers []string `toml:"handlers"`
}

type Cache struct {
	Enabled bool `toml:"enabled"`
	TTL     int  `toml:"ttl"`
	MaxSize int  `toml:"max_size"`
}

type Features struct {
	EnableAPI bool `toml:"enable_api"`
	RateLimit int  `toml:"rate_limit"`
}

func main() {
	var config Config

	if _, err := toml.DecodeFile("test.toml", &config); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Title: %sn", config.Title)
	fmt.Printf("Version: %sn", config.Version)
	fmt.Printf("Database Host: %sn", config.Database.Host)
	fmt.Printf("Database Port: %dn", config.Database.Port)
	fmt.Printf("Server Port: %dn", config.Server.Port)
	fmt.Printf("Cache Enabled: %tn", config.Cache.Enabled)
	fmt.Printf("Databases: %vn", config.Database.Databases)
}

Enjoy!


Condividi

Commentami!