Set of reusable components for Golang projects

go-utils

Go Report Card Go Reference

Table of contents

1. Overview

In my free time, I will learn new knowledge about Golang and make notes on this project, or more simply, I will write my own components that can be reused for many different projects. This helped me review my knowledge of Golang as well as gain more experience on how to use this language.

2. Install

  • Run command go get.
go get github.com/phamtai97/go-utils

3. Utils package

3.1 logger

  • I have wrapped the zap library for easy use in projects. Why zap? Because it is very fast.
  • How to use?
  • We only need to create it once and use it anywhere in the project. For example:
...
func main(){
    // write log to console
    // logger.InitProduction("")

    // write log to logs.log file
    if err := logger.InitProduction("./logs.log"); err != nil {
        fmt.Printf("Failed to init logger: %v\n", err)
    }
    defer logger.Sync()

    logger.Info("I am AJPham",
        zap.String("Hey, ", "I am a software engineer"),
        zap.Int("Age: ", 1997))
    logger.Error("I am AJPham",
        zap.String("Hey, ", "I am a software engineer"),
        zap.Int("Age: ", 1997))
}

// Result in file logs.log
// {"level":"INFO","ts":"2021-09-10 21:52:04.176","caller":"error/main.go:65","msg":"I am AJPham","Hey, ":"I am a software engineer","Age: ":1997}
// {"level":"ERROR","ts":"2021-09-10 21:52:04.176","caller":"error/main.go:69","msg":"I am AJPham","Hey, ":"I am a software engineer","Age: ":1997,"stacktrace":"main.main\n\t/Users/Documents/github/go-utils/cmd/error/main.go:69\nruntime.main\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/proc.go:203"}
  • Detailed examples can be see here.

3.2 error

  • This is a simple way to create errors in the project. It uses the github.com/pkg/errors package as the core.
  • How to use?
  • We can new error and use it. For example:
...
func main() {
    logger.InitProduction("")

    err := ero.New("Not found file")
    errA := err.AddStackTrace("Component A called")
    errB := errA.AddContextf("Component %s called", "B")

    if errB.Is(err) {
        logger.Info("Error B is err")
    }

    logger.Error("This is error wrapper", zap.Error(errB))
    logger.Error("This is error detail wrapper", zap.Error(errB.Detail()))
    logger.Error("This is root cause", zap.Error(errB.RootCause().Detail()))
    logger.Error("This is root cause", zap.String("Error string", err.Error()))
}

// Result
// {"level":"INFO","ts":"2021-09-10 21:55:29.840","caller":"error/main.go:66","msg":"Error B is err"}
// {"level":"ERROR","ts":"2021-09-10 21:50:15.523","caller":"error/main.go:65","msg":"This is error wrapper","error":"Component B called: Component A called: Not found file","stacktrace":"main.main\n\t/Users/Documents/github/go-utils/cmd/error/main.go:65\nruntime.main\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/proc.go:203"}
// {"level":"ERROR","ts":"2021-09-10 21:50:15.523","caller":"error/main.go:66","msg":"This is error detail wrapper","error":"Component B called: Component A called: Not found file","errorVerbose":"Not found file\ngo-utils/utils/error.New\n\t/Users/Documents/github/go-utils/utils/error/error.go:17\nmain.main\n\t/Users/Documents/github/go-utils/cmd/error/main.go:61\nruntime.main\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/proc.go:203\nruntime.goexit\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/asm_amd64.s:1357\nComponent A called\ngo-utils/utils/error.(*ErrorWrapper).AddStackTrace\n\t/Users/Documents/github/go-utils/utils/error/error.go:47\nmain.main\n\t/Users/Documents/github/go-utils/cmd/error/main.go:62\nruntime.main\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/proc.go:203\nruntime.goexit\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/asm_amd64.s:1357\nComponent B called","stacktrace":"main.main\n\t/Users/Documents/github/go-utils/cmd/error/main.go:66\nruntime.main\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/proc.go:203"}
// {"level":"ERROR","ts":"2021-09-10 21:50:15.523","caller":"error/main.go:67","msg":"This is root cause","error":"Not found file","errorVerbose":"Not found file\ngo-utils/utils/error.New\n\t/Users/Documents/github/go-utils/utils/error/error.go:17\nmain.main\n\t/Users/Documents/github/go-utils/cmd/error/main.go:61\nruntime.main\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/proc.go:203\nruntime.goexit\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/asm_amd64.s:1357","stacktrace":"main.main\n\t/Users/Documents/github/go-utils/cmd/error/main.go:67\nruntime.main\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/proc.go:203"}
// {"level":"ERROR","ts":"2021-09-10 21:50:15.523","caller":"error/main.go:68","msg":"This is root cause","Error string":"Not found file","stacktrace":"main.main\n\t/Users/Documents/github/go-utils/cmd/error/main.go:68\nruntime.main\n\t/usr/local/Cellar/[email protected]/1.13.11/libexec/src/runtime/proc.go:203"}
  • Detailed examples can be see here.

3.3 datetime

  • Working with Datetime in programming is inevitable. I provide a simple enough package to play with Datetime in Golang.
  • How to use?
  • It is easy.
func main() {
    logger.InitProduction("")

    // Convert current milliseconds to different formats
    logger.Info("Convert current milliseconds to format YYYY-MM-DD", zap.String("value", datetime.ConvertCurrentLocalTimeToString(datetime.YYYY_MM_DD)))
    logger.Info("Convert current milliseconds to format YYYY-MM-DD HH:mm:ss", zap.String("value", datetime.ConvertCurrentLocalTimeToString(datetime.YYYY_MM_DD_HH_MM_SS)))
    logger.Info("Convert current milliseconds to format YYYY-MM-DD HH:mm:ss.SSS", zap.String("value", datetime.ConvertCurrentLocalTimeToString(datetime.YYYY_MM_DD_HH_MM_SS_SSS)))
    logger.Info("Convert current milliseconds to format DD-MM-YYYY", zap.String("value", datetime.ConvertCurrentLocalTimeToString(datetime.DD_MM_YYYY)))
    logger.Info("Convert current milliseconds to format DD-MM-YYYY HH:mm:ss", zap.String("value", datetime.ConvertCurrentLocalTimeToString(datetime.DD_MM_YYYY_HH_MM_SS)))
    logger.Info("Convert current milliseconds to format DD-MM-YYYY HH:mm:ss.SSS", zap.String("value", datetime.ConvertCurrentLocalTimeToString(datetime.DD_MM_YYYY_HH_MM_SS_SSS)))

    // Get current millisenconds
    currMillis := datetime.GetCurrentMiliseconds()
    logger.Info("Current milliseconds", zap.Int64("value", millis))

    // Convert milliseconds to specific string
    ddmmyyyy_hhmmss_sss := datetime.ConvertMillisecondsToString(currMillis, datetime.DD_MM_YYYY_HH_MM_SS_SSS)
    logger.Info("Convert milliseconds to format DD-MM-YYYY HH:mm:ss.SSS", zap.String("value", ddmmyyyy_hhmmss_sss))

    // Convert specific string to milliseconds
    millis, err := datetime.ConvertStringToMilliseconds("2021-09-09 09:09:09.999", datetime.YYYY_MM_DD_HH_MM_SS_SSS)
    if err != nil{
        logger.Error("Failed to convert", zap.Error(err))
    }
    logger.Info("Convert string format YYYY-MM-DD HH:mm:ss.SSS to millisecond", zap.Int64("value", millis))

    // other functions
    logger.Info("Start local time of year", zap.Int64("value", datetime.ConvertLocalTimeToMilliseconds(datetime.GetStartLocalTimeOfYear())))
    logger.Info("End local time of year", zap.Int64("value", datetime.ConvertLocalTimeToMilliseconds(datetime.GetEndLocalTimeOfYear())))
    logger.Info("Start local time of month", zap.Int64("value", datetime.ConvertLocalTimeToMilliseconds(datetime.GetStartLocalTimeOfMonth())))
    logger.Info("End local time of month", zap.Int64("value", datetime.ConvertLocalTimeToMilliseconds(datetime.GetEndLocalTimeOfMonth())))
    logger.Info("Start local time of day", zap.Int64("value", datetime.ConvertLocalTimeToMilliseconds(datetime.GetStartLocalTimeOfDay())))
    logger.Info("End local time of day", zap.Int64("value", datetime.ConvertLocalTimeToMilliseconds(datetime.GetEndLocalTimeOfDay())))
    logger.Info("Start local time of time", zap.Int64("value", datetime.ConvertLocalTimeToMilliseconds(datetime.GetStartLocalTimeOfTime(time.Now()))))
    logger.Info("Start local time of time", zap.Int64("value", datetime.ConvertLocalTimeToMilliseconds(datetime.GetEndLocalTimeOfTime(time.Now()))))
    logger.Info("Get before local time of time", zap.Int64("value", datetime.ConvertLocalTimeToMilliseconds(datetime.GetBeforeLocalTimeOfTime(time.Now(), 9, true))))
    logger.Info("Get after local time of time", zap.Int64("value", datetime.ConvertLocalTimeToMilliseconds(datetime.GetAfterLocalTimeOfTime(time.Now(), 9, false))))
}
  • Detailed examples can be see here.
Owner
AJPham
Software Engineering (Java, Golang, JS, C++)
AJPham
Similar Resources

set and get github user statuses

gh user-status being an extension for interacting with the status on a GitHub profile. gh user-status set gh user-status set interactively set status

Nov 19, 2022

Generate FIRST/FOLLOW/PREDICT Set from BNF.

Generate FIRST/FOLLOW/PREDICT Set from BNF. We can use it to study parser theory. Feature FirstSet generate. Output pretty. FollowSet generate. Output

Oct 30, 2021

Set of functions/methods that will ease GO code generation

Set of functions/methods that will ease GO code generation

Dec 1, 2021

Tanzu Framework provides a set of building blocks to build atop of the Tanzu platform and leverages Carvel packaging

Tanzu Framework provides a set of building blocks to build atop of the Tanzu platform and leverages Carvel packaging and plugins to provide users with a much stronger, more integrated experience than the loose coupling and stand-alone commands of the previous generation of tools.

Dec 16, 2022

API and a set of tools to manage Netbox configuration declaratively

declarative-netbox An experimental project to explore the idea of managing the N

Jan 24, 2022

Set of scripts & tools for converting between numbers and major system encoded words.

Set of scripts & tools for converting between numbers and major system encoded words.

major-system-converter Set of scripts & tools for converting between numbers and major system encoded words. Uses phonetics instead of letters to conv

Aug 9, 2022

Golang CS:GO external base. Development currently halted due to compiler/runtime Golang bugs.

gogo Golang CS:GO External cheat/base. Also, my first Golang project. Wait! Development momentarily halted due to compiler/runtime bugs. Disclaimer Th

Jun 25, 2022

Belajar Golang Install Golang

Golang belajar Golang Install Golang = download di https://golang.org/dl/ = pilih yg Zip = extract file zipnya = buka foldernya - copy folder go = pas

Nov 15, 2021

Golang-module-references - A reference for how to setup a Golang project with modules - Task Management + Math Examples

Golang Module Project The purpose of this project is to act as a reference for setting up future Golang projects using modules. This project has a mat

Jan 2, 2022
A tool to download and install TiDB components

What is TiUP tiup is a tool to download and install TiDB components. Documentati

Apr 14, 2022
The gofinder program is an acme user interface to search through Go projects.

The gofinder program is an acme user interface to search through Go projects.

Jun 14, 2021
James is your butler and helps you to create, build, debug, test and run your Go projects
James is your butler and helps you to create, build, debug, test and run your Go projects

go-james James is your butler and helps you to create, build, debug, test and run your Go projects. When you often create new apps using Go, it quickl

Oct 8, 2022
Visualize how a projects source code is distributed among its files and folders
Visualize how a projects source code is distributed among its files and folders

Source Code Visualizer Visualize the code distribution in a project. Applications Applications include: Visualizing code distribution for more educate

Jul 31, 2022
sentry integrated logrus package for our internal projects

sentry integrated logrus package for our internal projects

Oct 15, 2021
A boilerplate for building Gradescope autograders for Go projects.

go-autograder A boilerplate for building Gradescope autograders for Go projects. Getting started This autograder works by running all Go tests in a st

Nov 6, 2022
Auto-updates PaperMC Projects

Auto-updates PaperMC projects Motivation Paper has made it very difficult to auto update servers, because they discourage it. This means that you can'

Mar 15, 2022
A CLI for working with Go + Angular projects

NGGO A CLI tool for working with Angular + Go projects. Prerequisites You must have Go installed and GOPATH & GOBIN setup properly You must have angul

Feb 23, 2020
Go Programming specialization coding projects/assignments/scratchpads

Go-Coursework Go Programming specialization coding projects/assignments/scratchpads This repo contains coding assignments from the Coursera - Golang S

Feb 1, 2022
CapMonsterTool is a set of Go tools designed to simply make requests to the CapMonster Cloud API.

✨ CapMonsterTool ✨ About this module What is ✨ CapMonsterTool ✨ ? CapMonsterTool is a set of Go tools designed to simply make requests to the CapMonst

Dec 1, 2022