Waylon  Bruen

Waylon Bruen

1652410200

Toml: TOML Parser for Golang with Reflection

TOML stands for Tom's Obvious, Minimal Language. This Go package provides a reflection interface similar to Go's standard library json and xml packages.

This library requires Go 1.13 or newer; install it with:

% go get github.com/BurntSushi/toml@latest

It also comes with a TOML validator CLI tool:

% go install github.com/BurntSushi/toml/cmd/tomlv@latest
% tomlv some-toml-file.toml

Testing

This package passes all tests in toml-test for both the decoder and the encoder.

Examples

This package works similar to how the Go standard library handles XML and JSON. Namely, data is loaded into Go values via reflection.

For the simplest example, consider some TOML file as just a list of keys and values:

Age = 25
Cats = [ "Cauchy", "Plato" ]
Pi = 3.14
Perfection = [ 6, 28, 496, 8128 ]
DOB = 1987-07-05T05:45:00Z

Which could be defined in Go as:

type Config struct {
    Age        int
    Cats       []string
    Pi         float64
    Perfection []int
    DOB        time.Time // requires `import time`
}

And then decoded with:

var conf Config
_, err := toml.Decode(tomlData, &conf)
// handle error

You can also use struct tags if your struct field name doesn't map to a TOML key value directly:

some_key_NAME = "wat"
type TOML struct {
    ObscureKey string `toml:"some_key_NAME"`
}

Beware that like other most other decoders only exported fields are considered when encoding and decoding; private fields are silently ignored.

Using the Marshaler and encoding.TextUnmarshaler interfaces

Here's an example that automatically parses duration strings into time.Duration values:

[[song]]
name = "Thunder Road"
duration = "4m49s"

[[song]]
name = "Stairway to Heaven"
duration = "8m03s"

Which can be decoded with:

type song struct {
    Name     string
    Duration duration
}
type songs struct {
    Song []song
}
var favorites songs
if _, err := toml.Decode(blob, &favorites); err != nil {
    log.Fatal(err)
}

for _, s := range favorites.Song {
    fmt.Printf("%s (%s)\n", s.Name, s.Duration)
}

And you'll also need a duration type that satisfies the encoding.TextUnmarshaler interface:

type duration struct {
    time.Duration
}

func (d *duration) UnmarshalText(text []byte) error {
    var err error
    d.Duration, err = time.ParseDuration(string(text))
    return err
}

To target TOML specifically you can implement UnmarshalTOML TOML interface in a similar way.

More complex usage

Here's an example of how to load the example from the official spec page:

# This is a TOML document. Boom.

title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
organization = "GitHub"
bio = "GitHub Cofounder & CEO\nLikes tater tots and beer."
dob = 1979-05-27T07:32:00Z # First class dates? Why not?

[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true

[servers]

  # You can indent as you please. Tabs or spaces. TOML don't care.
  [servers.alpha]
  ip = "10.0.0.1"
  dc = "eqdc10"

  [servers.beta]
  ip = "10.0.0.2"
  dc = "eqdc10"

[clients]
data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it

# Line breaks are OK when inside arrays
hosts = [
  "alpha",
  "omega"
]

And the corresponding Go types are:

type tomlConfig struct {
    Title   string
    Owner   ownerInfo
    DB      database `toml:"database"`
    Servers map[string]server
    Clients clients
}

type ownerInfo struct {
    Name string
    Org  string `toml:"organization"`
    Bio  string
    DOB  time.Time
}

type database struct {
    Server  string
    Ports   []int
    ConnMax int `toml:"connection_max"`
    Enabled bool
}

type server struct {
    IP string
    DC string
}

type clients struct {
    Data  [][]interface{}
    Hosts []string
}

Note that a case insensitive match will be tried if an exact match can't be found.

A working example of the above can be found in _example/example.{go,toml}.

Compatible with TOML version v1.0.0.

Documentation: https://godocs.io/github.com/BurntSushi/toml

See the releases page for a changelog; this information is also in the git tag annotations (e.g. git show v0.4.0).

Author: BurntSushi
Source Code: https://github.com/BurntSushi/toml 
License: MIT license

#go #golang #toml 

What is GEEK

Buddha Community

Toml: TOML Parser for Golang with Reflection
Waylon  Bruen

Waylon Bruen

1652410200

Toml: TOML Parser for Golang with Reflection

TOML stands for Tom's Obvious, Minimal Language. This Go package provides a reflection interface similar to Go's standard library json and xml packages.

This library requires Go 1.13 or newer; install it with:

% go get github.com/BurntSushi/toml@latest

It also comes with a TOML validator CLI tool:

% go install github.com/BurntSushi/toml/cmd/tomlv@latest
% tomlv some-toml-file.toml

Testing

This package passes all tests in toml-test for both the decoder and the encoder.

Examples

This package works similar to how the Go standard library handles XML and JSON. Namely, data is loaded into Go values via reflection.

For the simplest example, consider some TOML file as just a list of keys and values:

Age = 25
Cats = [ "Cauchy", "Plato" ]
Pi = 3.14
Perfection = [ 6, 28, 496, 8128 ]
DOB = 1987-07-05T05:45:00Z

Which could be defined in Go as:

type Config struct {
    Age        int
    Cats       []string
    Pi         float64
    Perfection []int
    DOB        time.Time // requires `import time`
}

And then decoded with:

var conf Config
_, err := toml.Decode(tomlData, &conf)
// handle error

You can also use struct tags if your struct field name doesn't map to a TOML key value directly:

some_key_NAME = "wat"
type TOML struct {
    ObscureKey string `toml:"some_key_NAME"`
}

Beware that like other most other decoders only exported fields are considered when encoding and decoding; private fields are silently ignored.

Using the Marshaler and encoding.TextUnmarshaler interfaces

Here's an example that automatically parses duration strings into time.Duration values:

[[song]]
name = "Thunder Road"
duration = "4m49s"

[[song]]
name = "Stairway to Heaven"
duration = "8m03s"

Which can be decoded with:

type song struct {
    Name     string
    Duration duration
}
type songs struct {
    Song []song
}
var favorites songs
if _, err := toml.Decode(blob, &favorites); err != nil {
    log.Fatal(err)
}

for _, s := range favorites.Song {
    fmt.Printf("%s (%s)\n", s.Name, s.Duration)
}

And you'll also need a duration type that satisfies the encoding.TextUnmarshaler interface:

type duration struct {
    time.Duration
}

func (d *duration) UnmarshalText(text []byte) error {
    var err error
    d.Duration, err = time.ParseDuration(string(text))
    return err
}

To target TOML specifically you can implement UnmarshalTOML TOML interface in a similar way.

More complex usage

Here's an example of how to load the example from the official spec page:

# This is a TOML document. Boom.

title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
organization = "GitHub"
bio = "GitHub Cofounder & CEO\nLikes tater tots and beer."
dob = 1979-05-27T07:32:00Z # First class dates? Why not?

[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true

[servers]

  # You can indent as you please. Tabs or spaces. TOML don't care.
  [servers.alpha]
  ip = "10.0.0.1"
  dc = "eqdc10"

  [servers.beta]
  ip = "10.0.0.2"
  dc = "eqdc10"

[clients]
data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it

# Line breaks are OK when inside arrays
hosts = [
  "alpha",
  "omega"
]

And the corresponding Go types are:

type tomlConfig struct {
    Title   string
    Owner   ownerInfo
    DB      database `toml:"database"`
    Servers map[string]server
    Clients clients
}

type ownerInfo struct {
    Name string
    Org  string `toml:"organization"`
    Bio  string
    DOB  time.Time
}

type database struct {
    Server  string
    Ports   []int
    ConnMax int `toml:"connection_max"`
    Enabled bool
}

type server struct {
    IP string
    DC string
}

type clients struct {
    Data  [][]interface{}
    Hosts []string
}

Note that a case insensitive match will be tried if an exact match can't be found.

A working example of the above can be found in _example/example.{go,toml}.

Compatible with TOML version v1.0.0.

Documentation: https://godocs.io/github.com/BurntSushi/toml

See the releases page for a changelog; this information is also in the git tag annotations (e.g. git show v0.4.0).

Author: BurntSushi
Source Code: https://github.com/BurntSushi/toml 
License: MIT license

#go #golang #toml 

Hire Dedicated Golang Developers | Golang Web Development Company

Does your business need a robust system across large-scale network servers then developing your app with a Golang programming language is the way to go. Golang is generally used for the development of highly secured, High Speed and High Modularity apps such as a FinTech Industry.

Want to develop a Highly secured app for your business?

Then hire a dedicated Golang developer from WebClues Infotech that are highly skilled in carrying out the work in a timely and qualitative output. With WebClues Infotech you get the assurance that we know what are the customers’ expectations and how to deliver on them on time.

Get your desired Golang Developer based on your project requirement!!

Share your requirements here https://www.webcluesinfotech.com/contact-us/

Book Free Interview with Golang developer: https://bit.ly/3dDShFg

#hire golang developer #hire go language developer #dedicated golang app developers #golang web development company #hire golang developers india #hire expert golang developers

Veronica  Roob

Veronica Roob

1653788820

TOML: A PHP Parser For TOML

TOML parser for PHP

A PHP parser for TOML compatible with TOML v0.4.0.

Installation

Requires PHP >= 7.1.

Use Composer to install this package:

composer require yosymfony/toml

Usage

You can parse an inline TOML string or from a file:

To parse an inline TOML string:

use Yosymfony\Toml\Toml;

$array = Toml::Parse('key = [1,2,3]');

print_r($array);

To parse a TOML file:

$array = Toml::ParseFile('example.toml');

print_r($array);

Additionally, methods parse and parseFile accept a second argument called resultAsObject to return the result as an object based on stdClass.

$object = Toml::Parse('key = [1,2,3]', true);

TomlBuilder

You can create a TOML string with TomlBuilder. TomlBuilder uses a fluent interface for more readable code:

    use Yosymfony\Toml\TomlBuilder;

    $tb = new TomlBuilder();

    $result = $tb->addComment('Toml file')
        ->addTable('data.string')
        ->addValue('name', "Toml", 'This is your name')
        ->addValue('newline', "This string has a \n new line character.")
        ->addValue('winPath', "C:\\Users\\nodejs\\templates")
        ->addValue('literal', '@<\i\c*\s*>') // literals starts with '@'.
        ->addValue('unicode', 'unicode character: ' . json_decode('"\u03B4"'))

        ->addTable('data.bool')
        ->addValue('t', true)
        ->addValue('f', false)

        ->addTable('data.integer')
        ->addValue('positive', 25, 'Comment inline.')
        ->addValue('negative', -25)

        ->addTable('data.float')
        ->addValue('positive', 25.25)
        ->addValue('negative', -25.25)

        ->addTable('data.datetime')
        ->addValue('datetime', new \Datetime())

        ->addComment('Related to arrays')

        ->addTable('data.array')
        ->addValue('simple', array(1,2,3))
        ->addValue('multiple', array(
            array(1,2),
            array('abc', 'def'),
            array(1.1, 1.2),
            array(true, false),
            array( new \Datetime()) ))

        ->addComment('Array of tables')

        ->addArrayOfTable('fruit')                            // Row
            ->addValue('name', 'apple')
            ->addArrayOfTable('fruit.variety')
                ->addValue('name', 'red delicious')
            ->addArrayOfTable('fruit.variety')
                ->addValue('name', 'granny smith')
        ->addArrayOfTable('fruit')                            // Row
            ->addValue('name', 'banana')
            ->addArrayOfTable('fruit.variety')
                ->addValue('name', 'plantain')
        ->getTomlString();    // Generate the TOML string

The result:

#Toml file

[data.string]
name = "Toml" #This is your name
newline = "This string has a \n new line character."
winPath = "C:\\Users\\nodejs\\templates"
literal = '<\i\c*\s*>'
unicode = "unicode character: δ"

[data.bool]
t = true
f = false

[data.integer]
positive = 25 #Comment inline.
negative = -25

[data.float]
positive = 25.25
negative = -25.25

[data.datetime]
datetime = 2013-06-10T21:12:48Z

#Related to arrays

[data.array]
simple = [1, 2, 3]
multiple = [[1, 2], ["abc", "def"], [1.1, 1.2], [true, false], [2013-06-10T21:12:48Z]]

# Array of tables

[[fruit]]
name = "apple"

[[fruit.variety]]
name = "red delicious"

[[fruit.variety]]
name = "granny smith"

[[fruit]]
name = "banana"

[[fruit.variety]]
name = "plantain"

Limitations

The TomlBuilder class is an utility to get Toml strings that has the following limitations:

  • Only admits basic strings and literal strings.

Deprecated method

The following method will be eliminated in version 2.0.0

  • [TomlBuilder] addArrayTables

Contributing

When Contributing code to this library, you must follow its coding standards. Toml follows PSR-2 coding style. To ensure the CS, you can use the CLI tool PHP-CS-Fixer.

Unit tests

You can run the unit tests with the following command:

$ cd toml
$ composer test

License

This library is open-sourced software licensed under the MIT license.

Author: yosymfony
Source Code: https://github.com/yosymfony/toml
License: MIT License

#php #toml 

Golang Web Development:Th Best Programming Language in 2020

https://www.mobinius.com/blogs/golang-web-development-company

#golang web development #golang-app-development-company #golang-development-solutions #hire-golang-developers #golang-development-services

Vincent Lab

Vincent Lab

1605177275

Working with TOML in JavaScript

In this video I’m going to be showing you how to work with TOML using Node.js

#toml #parser #programming #toml decoder #coding