Last active
October 26, 2021 19:30
-
-
Save tomcam/3a0002119d60435505bff426b9345ae7 to your computer and use it in GitHub Desktop.
Go/Golang: writes a struct to a YAML file, then reads it back from the YAML as a map using the gopkg.in/yaml package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"gopkg.in/yaml.v3" | |
"os" | |
) | |
type Theme struct { | |
Name string `yaml:"name"` | |
Branding string `yaml:"branding"` | |
Description string `yaml:"description"` | |
} | |
type Config struct { | |
Theme `yaml:"Settings"` | |
} | |
func main() { | |
filename := "./config.yaml" | |
config := Config{ | |
Theme: Theme{Name: "Debut", | |
Branding: "Debut by Metabuzz", | |
Description: "Perfect theme to showcase a new product"}} | |
b, err := yaml.Marshal(&config) | |
if err != nil { | |
panic(err) | |
} | |
err = ioutil.WriteFile(filename, b, os.ModePerm) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("Created file %v\n", filename) | |
/* The generated file looks like this: | |
Settings: | |
name: Debut | |
branding: Debut by Metabuzz | |
description: Perfect theme to showcase a new product | |
*/ | |
b, err = ioutil.ReadFile(filename) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("Read file %v\n", filename) | |
themeMap := make(map[string]Theme) | |
err = yaml.Unmarshal(b, &themeMap) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("File contents as a map: %#v\n", themeMap) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment