Common Utilities in Golang Project
Index of GoLang Resources
- How to install Go? | Chapter 1 |
- Creating Your First GoLang Project |Chapter 2 |
- GoLang Language Fundamentals | Chapter 3 |
- Control Flow in GoLang | Chapter 4 |
- GoLang Data Structures | Chapter 5.1 |
- GoLang Data Structures | Chapter 5.2 |
- GoLang Concurrency | Chapter 6 |
- Error Handling in GoLang | Chapter 7 |
- Common Utilities in GoLang Project | Chapter 8 |
- GoLang Database/SQL | Chapter 9 |
- GO with GORM | Chapter 10 |
Common Utilities in Project
In Chapter-7 of our Golang Tutorial, we touched upon ‘Error Handling’ in Golang. In this chapter, let’s explore ‘Common Utilities in Golang Project’.
Properties File Scanner –
Golang is having a support library for reading and writing properties files. It supports reading the key values from multiple properties file and in Spring style manner like ${key} to the corresponding value.
Value expressions refer to other keys like in ${key}.
We can decode the properties into struct, maps, arrays & values through struct tags.
It is like java properties scanner forgo.
For more info refer https://github.com/magiconair/properties
Package properties provide functions for reading and writing ISO-8859-1 and UTF-8 encoded .properties files and have support for recursive property expansion.
Java properties files are ISO-8859-1 encoded and use Unicode literals for characters outside the ISO character set. Unicode literals can be used in UTF-8 encoded properties files but aren’t necessary.
Just download this dependency, import its packages, create a properties file in key, value format and use the functions for accessing values of keys.
To load a single properties file, we must have to use –
p:=Properties.MustLoadFile(filename,properties.UTF8)
To load multiple properties files use MustLoadFiles() which loads the files in the given order and merges the result. Missing properties files can be ignored if the ‘ignoreMissing‘ flag is set to true.
Filenames can contain environment variables which are expanded before loading.
Type below on your command prompt for downloading dependency –
>go get -u github.com/magiconair/properties
I have created two properties file exception.properties and message.properties file in my project location
golangdemo/src/mindbowser/config/message.properties
All of the different key/value delimiters ‘ ‘, ‘:’ and ‘=’ are supported as well as the comment characters ‘!’ and ‘#’ and multi-line values.
! this is a comment # and so is this
# the following expressions are equal
-
key value
-
key=value
-
key: value
-
key = value
-
key: value
-
key = val\
Now to load the properties file from the location you need to import the package
import “github.com/magiconair/properties”
Now load the multiple properties like this –
var PropertyFile= []string{“${HOME}/golangdemo/src/mindbowser/config/exception.properties”, “${HOME}/golangdemo/src/mindbowser/config/message.properties”} var P, _ = properties.LoadFiles(PropertyFile, properties.UTF8, true)
This will load all the properties from your location specified and store into Preference variable.
Now access the values based on keys using –
P.MustGet(“”)
OR
P.Get(“”) /* If key not found it will return panic error*/
Here, we will see the standard approach followed in projects like the actual use of properties file.
Now, see how to deal with properties files –
Here, I’ve created standard directory structure :
I’ve created two properties files as shown below –
Now I’ve created constants file and mapped the messages and these messages are keys of the properties file that we are going to read.
Now here I’ve created ResourceManager struct that is scanning properties file and by using the function it will read the associated value of its key.
In the above code, as given, I’ve imported github.com/magiconair/properties dependency and loaded properties file. Here, GetProperty(string) function will accept the string value and again using Get( ) it will read.
So your output would be –
We can deal with the properties file in many no. of ways, to read more about this properties file scanner library package, visit this link https://github.com/magiconair/properties
Logger in Go
Go has support for logging which is implemented in “log” package. It defines a type, Logger, with methods for formatting output. It also has a predefined ‘standard‘ Logger accessible through functions Printf/Println, Fatalf/Fatalln, and Panicf/Panicle, which are easier to use than creating a Logger manually. That logger writes to standard error and prints the date and time of each logged message.
For more info about this log package visit: https://golang.org/pkg/log/
But I have used other libraries implemented by some other developers. So we will look into this logger. Basically, the logger is used to log the application specific messages. We use loggers to write the log messages to file so in case if the application gets some error we can check the log messages into the log file.
So here I’ve used https://github.com/sirupsen/logrus logger which is really having the efficient implementation of the logger and providing complete compatibility like the logger.
For this, we have to import the below dependency github.com/sirupsen/logrus. This API has provided complete functionality like log4j logger in java.
Again I’ve imported gopkg.in/natefinch/lumberjack.v2 dependency that will create and maintain like –
The maximum file size will be 1MB and when the file exceeds this limit then it will create a new log file. MaxBackups field tells that it will keep maximum 3 backup files and MaxAge tells that this file will remain in the system for 28 days. Like this, I have created the configuration but you can change it depending on your requirements.
The log file will be created like this –
Getter Setter in Go
The getter setter is the functionality of OOPs i.e. Encapsulation. In Java, we can create the getter setter methods to set and get the values of fields. Like Java, we also can create the getter and setters in Go and can provide data hiding (if you wish to). Normally in Eclipse IDE (the most preferred IDE by java professionals), we can generate getter setters by choosing the option “Generate getter setter” but here in Go, we have to create getter/setter manually.
The O/p will be as expected –
Copier for Go – Copy value from one struct to another struct and more
Sometimes in the project, there could be the need for copying one struct/slice to another. So if we try to do it manually we need to put more efforts. So there is one library that is providing this feature.
So to do this kind of work, we need to import github.com/jinzhu/copier dependency.
The output will be like this. Non-matched fields will be ignored.