Common Utilities in Golang 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 supportive 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 for go.
Package properties provides functions for reading and writing ISO-8859-1 and UTF-8 encoded .properties files and has 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 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 –
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
I have created two properties file and file in my project location
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 = value
Now to load the properties file from the location you need to import the package
import “”
Now load the multiple properties like this –
var PropertyFile= []string{"${HOME}/golangdemo/src/mindbowser/config/", "${HOME}/golangdemo/src/mindbowser/config/"}

var P, _ = properties.LoadFiles(PropertyFile, properties.UTF8, true)
This will load all the properties from your location specified and store into P reference variable.
Now access the values based on keys using –
P.MustGet(“<Name of Key>”)
 P.Get(“<Name of Key>”) /* 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 a 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 properties file that we are going to read.

package constants

var (
 LOGIN_SUCCESS = "message.login.success"
 LOGOUT_SUCCESS = "message.logout.success"
 LOGOUT_FAILED = "message.logout.failed"
 USER_NOT_EXIST = "user.not.exist"
 SERVER_NOT_RESPONDING = "server.not.responding"
 SERVER_ERROR = "internal.problem"
 NOT_FOUND = "not.found"
 EXCEPTION_DAO_USER = "exception.user.dao"

Now here I’ve created ResourceManager struct that is scanning properties file and by using function it will read associated value of its key.

 package utils

import (

var PropertyFiles = []string{"${GOPATH}/src/PropertiesScanner/resources/",

var Props, _ = properties.LoadFiles(PropertyFiles, properties.UTF8, true)

type ResourceManager struct {

func (res ResourceManager) GetProperty(propertyName string) string {
 message := ""
 var ok bool
 message, ok = Props.Get(propertyName)
 if !ok {
 return Props.MustGet("not.found")
 } else {
 return message
In above code, as given, I’ve imported dependency and loaded properties file. Here, GetProperty(string) function will accept the string value and again using Get( ) it will read.

 package main
import (

func main() {

 //Reading values from properties file

 /*Here I have created ResourceManager struct like we are using
 in java to read the properties file. So I've mapped the constants 
 with the messages from properties file. It is a standard approach to
 read the values from properties file */

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

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/Panicln, 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:
But I have used other libraries implemented by some other developers. So we will look into this logger. Basically logger is used to log the application-specific messages. We use loggers to write the log messages to file so in case if an application gets some error we can check the log messages into the log file.
So here I’ve used logger which is really having an efficient implementation of a logger and providing complete compatibility like a logger.
For this, we have to import the below dependency This API has provided complete functionality like log4j logger in java.
Again I’ve imported dependency that will create and maintain like –
 Filename: "./LogDemo.log",
 MaxSize: 1, // megabytes after which new file is created
 MaxBackups: 3, // number of backups
 MaxAge: 28, //days
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 system for 28 days. Like this, I have created the configuration but you can change it depending on your requirements.

 package main
log ""
func init() {
 log.SetFormatter(&log.JSONFormatter{}) //Choose any format
 file, err := os.OpenFile("LogDemo.log",
os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)

if err == nil {
 Filename: "./LogDemo.log",
MaxSize: 1, // megabytes after which new file //created
 MaxBackups: 3, // number of backups
 MaxAge: 28, //days
 log.Println(file.Name(),"is generated log file") 
 } else {
 log.Info("Failed to log to file, using default stderr") 
func main(){
 log.Info("Main Function Started")
 SaveUser() //Calling SaveUser()
func SaveUser(){
 //log messages by specifying log level
 log.Info("SaveUser Success") //to specify info messages
 log.Error("Error while saving user") //to specify error messages
The log file will be created like this –

Are you looking for Golang development services?

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 option “Generate getter setter” but here in Go we have to create getter/setter manually.  
package model
type UserModel struct {
 userName string 
 email string 
 password string 

func (user *UserModel) SetuserName(userName string) {
 user.userName = userName

func (user *UserModel) GetuserName() string {
 return user.userName

func (user *UserModel) Setemail(email string) { = email

func (user UserModel) Getemail() string {
func (user *UserModel) Setpassword(password string) {
 user.password = password

func (user UserModel) GetPassword() string {
 return user.password

package main

func main(){

 //Create object of struct UserModel

 user.SetuserName("John Martin")

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 dependency.

package main
import (
type User struct {
 Name string
 Age int32
type Employee struct {
 Name string
 Age int32
 DoubleAge int32
 EmployeId int64
func main() {
 var (
 user = User{Name: "John", Age: 18}
 users = []User{{Name: "Martin", Age: 18}, 
 {Name: "Ricky", Age: 30}}
 employee = Employee{}
 employees = []Employee{}
 //Copy field to field
 copier.Copy(&employee, &user)
 // Copy struct to slice
 copier.Copy(&employees, &user)
 // Copy slice to slice
 employees = []Employee{}
 copier.Copy(&employees, &users)
The output will be like this. Non-matched fields will be ignored.
To know more about this, visit –

subscribe to our newsletter

Related Posts

Leave a Comment