Golang YAML to JSON with Gin
You have a YAML file and you want to display these informations in a HTTP API with a JSON result. So you need to read the file then binding YAML datas (keys and values) and display to JSON.
What do we need ?
We need a micro framework and to bind YAML, Gin and YAML.
go get gopkg.in/gin-gonic/gin.v1 && go get gopkg.in/yaml.v2
The YAML file
Create the YAML file named “config.yml”.
'title': 'My first article'
'email': 'go@email.com'
'tags': [go, golang, yaml, json]
So, keys are “title”, “email” and “tags” (the last is a string array).
The script
Create a “main.go” file.
package mainimport (
"log"
"io/ioutil" "gopkg.in/gin-gonic/gin.v1"
"gopkg.in/yaml.v2"
)type Config struct {
Title string `json:"title"`
Email string `json:"email"`
Tags []string `json:"tags"`
}func main() {
r := gin.Default() r.GET("", func(c *gin.Context) {
// The next
}) r.Run(":3000")
}
As you can see, we load libraries then we declare a struct named “Config” with our 3 keys present in the YAML file.
Load the YAML file
For loading the file, we use the native function “ReadFile” from “ioutil”.
data, err := ioutil.ReadFile("config.yml")
if err != nil {
log.Fatalf("error: %v", err)
}
Binding YAML datas
We gonna use the “Unmarshal” function from “Yaml” library.
var config Config
err = yaml.Unmarshal([]byte(data), &config)
if err != nil {
log.Fatalf("error: %v", err)
}
And we put these datas in a new var “result”.
result := Config{
Title: config.Title,
Email: config.Email,
Tags: config.Tags,
}
Display JSON result
With Gin it’s very simple, we just need to use the “c.JSON” function.
c.JSON(200, result)
Result & final code
After starting the server, you will get a JSON result.
{"title":"This is my go blog","email":"go@email.com","tags":["go","golang","yaml","json"]}
Sources
- Gin : https://github.com/gin-gonic/gin
- YAML : https://github.com/go-yaml/yaml
- YAML Lint : http://www.yamllint.com