My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Set Indentation on New Golang YAML v3 Library

Tom Skellan's photo
Tom Skellan
·Jun 23, 2020

The new yaml go library gopkg.in/yaml.v3, bring new features such as node or more customization such as set indentation on the encoder.

so first thing first, we need to import the library

import (
    "gopkg.in/yaml.v3"
)

Remember that the v2 version does not support set indentation feature. Then, you need to set the struct that acts like a schema for your yaml file (we can use node representation, but on this tutorial, i will use traditional one)

type IamRole struct {
    Roles []IamRoleSpecific `yaml:"roles"`
}

type IamRoleSpecific struct {
    Name    string                    `yaml:"name"`
    Members []IamRoleSpecificProperty `yaml:"members"`
}

type IamRoleSpecificProperty struct {
    Id   string `yaml:"id"`
    Name string `yaml:"name"`
}

Next, load the yaml file

var role IamRole
var b bytes.Buffer
originFile, _ := ioutil.ReadFile("iam_config.yaml")
yaml.Unmarshal(originFile, &role)

now role variable contain the data that we can process

yamlEncoder := yaml.NewEncoder(&b)
yamlEncoder.SetIndent(2) // this is what you're looking for
yamlEncoder.Encode(&role)

ioutil.WriteFile("iam_config.yaml", b.Bytes(), 0664)

voila, the iam_config.yaml file is overwritten by our newly encoded yaml with 2 indentation.

for YAML file validator or checker, you can use YAML validator, and for check whether csv valid or not and get the reason why it is not valid csv format, you can check csv checker