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 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 –
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 propertie file exception.properties and message.properties file in my project location
golangdemo/src/mindbowser/config/exception.properties
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 = value
Now to load the properties file from 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 P reference variable.
Now access the values based on keys using –
P.MustGet(“<Name of Key>”)
OR
 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 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.
DemoConstants.go

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.
ResourceManager.go

 package utils

import (
 "github.com/magiconair/properties" 
)

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

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 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.
main.go

 package main
import (
 "PropertiesScanner/utils"
 "PropertiesScanner/constants"
 "fmt"
)

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 */

 resourceManager:=utils.ResourceManager{};
 successMsg:=resourceManager.GetProperty(constants.LOGIN_SUCCESS)
 notFoundMsg:=resourceManager.GetProperty(constants.NOT_FOUND)
 fmt.Println(successMsg)
 fmt.Println(notFoundMsg)
}
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/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 : https://golang.org/pkg/log/
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 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 efficient implementation of logger and providing complete compatibility like 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 –
&lumberjack.Logger{
 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 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.
main.go

 package main
import(
log "github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
 "os" 
)
func init() {
 //log.SetFormatter(&log.TextFormatter{})
 log.SetFormatter(&log.JSONFormatter{}) //Choose any format
 //log.SetOutput(os.Stdout)
 file, err := os.OpenFile("LogDemo.log",
os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)

if err == nil {
 log.SetOutput(
 &lumberjack.Logger{
 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
 log.Debug("Debug")
 log.Warn("Warning")
}
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 option “Generate getter setter” but here in Go we have to create getter/setter manually.  
UserModel.go
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) {
 user.email = email
}

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

func (user UserModel) GetPassword() string {
 return user.password
}
main.go

package main

import
(
 "GetterSetter/model"
 "fmt"
)
func main(){

 //Create object of struct UserModel

 user:=model.UserModel{}
 user.SetuserName("John Martin")
 user.GetuserName()
 user.Setemail("john_martin@gmail.com")
 user.Getemail()
 user.Setpassword("johnMartin234")
 user.GetPassword()
 fmt.Println(user)

}
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 of 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.
main.go

package main
import (
 "fmt"
 "github.com/jinzhu/copier" 
 )
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)
 fmt.Println(employee)
 // Copy struct to slice
 copier.Copy(&employees, &user)
 fmt.Println(employees)
 // Copy slice to slice
 employees = []Employee{}
 copier.Copy(&employees, &users)
 fmt.Println(employees) 
}
The output will be like this. Non-matched fields will be ignored.
To know more about this, visit – https://github.com/jinzhu/copier .

subscribe to our newsletter

   
   
Related Posts

Leave a Comment

go-with-ormdeploying-go-app-onaws-ec2-server