GO-vatar series: Yaml surfing
“YAML is a human-friendly data serialization standard for all programming languages” — https://yaml.org/.
Who here likes to use Yaml for data storage? *Me~~~~~*
Same with another programming language, in Golang we can also use Yaml to help our code to be more data-oriented. No need to take a long time. Just check it out.
Please prepare our Yaml file first yaa.
Next, how to read that Yaml file in our code indeed.
The result will be like this.
Not too difficult, isn’t it?
The next level we’re gonna try is how to call a Golang function with Yaml. But before doing that, I want to explain about a package in Go that called reflect.
“Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type.” — https://golang.org/pkg/reflect/
If you’re hard to understand those sentences, let’s direct to this one.
“MethodByName returns a function value corresponding to the method of v with the given name” — https://golang.org/pkg/reflect/#Value.MethodByName
Yes. With that function that has been provided by Go, we can call the function by dynamic name easily. So, we’ve already had this key in our Yaml file.
methods:f : Foob : Bar
That means we have func Foo and func Bar somewhere in our .go file which we want to call by using Yaml. We also already have a struct that have this.
Methods map[string]string
First, we need 2 new methods with the name Foo and Bar.
That needs a Example
struct. Next, we need another function to use reflect.
Please call exampleFunction()
in our main function. The full code will look like this.
Run with go run main.go
and the result will be like this.
Yeay we’ve called function Foo successfully. If you need to call func Bar instead, just change this exists := config.Methods["b"]
. Or for even better, we can create some looping code to call our function. Simple, right?
For the last of this article, I want to introduce another awesome package but this is outside Golang standard library. Please introduce https://github.com/goccy/go-yaml. It will support us more than the standard library could do.
Do you have fun with this surfing?! Because I do. — MperMperPisang