How to check for an empty object in Go

I typically perform comprehensive checks on various data structures (such as struct, array, slice, map, pointer, etc.) but prefer to avoid excessive if statements for object validation. Consequently, I developed a utility package for object validation to streamline this process, leveraging the capabilities of the Go reflection package. package check import ( "reflect" ) func IsEmpty(obj interface{}) bool { if obj == nil { return true } objValue := reflect.ValueOf(obj) switch objValue....

June 3, 2021 · 1 min · 127 words · Mecit Semerci

How to create a csv file in memory with golang

Sometimes you need to create an automatic report (invoice, bill) in CSV format. In such cases, it would be appropriate to keep it on blob storage instead of the server(container) disk. Now let’s see how we can do it using memory without saving to disk at all. package csvmanager import ( "bytes" "encoding/csv" "errors" ) func WriteAll(records [][]string) ([]byte, error) { if records == nil || len(records) == 0 { return nil, errors....

October 14, 2020 · 1 min · 166 words · Mecit Semerci

Golang json (Un)marshal custom date format

If we want to create a RESTFul API, we may need a date type field. Especially you are doing an integration API, the date format may not always be what you want. JSON serialization on GO can be annoying sometimes. In such cases, you can follow a method like that. go version 1.16 package customTypes import ( "errors" "fmt" "strings" "time" ) type JSONTime time.Time const DefaultFormat = time.RFC3339 var layouts = []string{ DefaultFormat, "2006-01-02T15:04Z", // ISO 8601 UTC "2006-01-02T15:04:05Z", // ISO 8601 UTC "2006-01-02T15:04:05....

August 24, 2020 · 2 min · 401 words · Mecit Semerci