Reading Configuration Files in Go
In case you are landing here directly, it’s suggested that you go and read through this for fundamentals.
In this blog, we shall be looking at following concepts :-
- Manage Dependencies in Go.
- Creation of Module in Go.
- Reading Configuration Files in Go.
Question:- Demonstrate, how do we manage dependencies in GO ?
Answer:- Here is the straight forward way to manage dependencies in Go :-
- Go Get tool installs one dependency at a time. And it installs the latest version of the package.
- Using a specific version of the package will also protect you from breaking changes the package might have. In Go 111, we got a new mod tool to handle dependency management.
Question:- How do we create a module in GO ?
Step #1.) Let’s first create a file called as “go.mod”. You can think of Go.mod as the packages you want.
Step #2.) At line #6, We are adding a requirement by mentioning the name of the package i.e. go-toml package, and we say the version of the package.
Step #3.) We can also see that, the new file is generated, called Go.sum. You can think of Go.sum as the packages that you actually require.
Step #4.) Once you want to upgrade the package, or add a new dependency, edit the Go.mod with a new dependency of the new version. Don’t forget to run your tests after upgrading to a new version.
Question:- Demonstrate, how can we read a Configuration File in GO ?
Answer:- Here is the straight forward way to read the files :-
Step #1.) We create a configuration object which has the login, which has the user and the password.
Step #2.) We now create the configuration object, into which we shall be reading the information from the configuration file :-
Step #3.) We now install the toml tool first, @ our working directory :-
Step #4.) We now import the necessary package, in order to read the configuration file well :-
Step #5.) Next, we perform following tasks in below snapshot :-
- At line #20, we now open the file, and as usual, validate the error, which should be not nil.
- At line #27, we use a new decoder for toml and then using the same decoder, we would read the configuration file and populate the configuration object directly.
That’s all in this section. If you liked reading this blog, kindly do press on clap button multiple times, to indicate your appreciation. We would see you in next series.