Skip to content

Instantly share code, notes, and snippets.

@lummie
lummie / exit.go
Created September 21, 2023 17:27
Wait for graceful exit.. [k8s, pod, cli]
/*
Waits for a terminate | interrupt signal, ctrl-c before finishing main
when creating services and adapters, I like to return a cleanup function that is deferred for
each service, thus when the app closes they are teared down in reverse order.
graceful.Exit() returns two functions:
- waitFor - which is called as the last statement of main. This will block until a signal to terminate or interrupt the executable.
- deferMe - defer this first before the service cleanups. This ensures thar stdout/err are flushed and sleeps 1 second before exiting.
@lummie
lummie / custom_time.go
Last active April 7, 2024 21:34
Golang custom date / time formats when marshalling to JSON
// CustomTime provides an example of how to declare a new time Type with a custom formatter.
// Note that time.Time methods are not available, if needed you can add and cast like the String method does
// Otherwise, only use in the json struct at marshal/unmarshal time.
type CustomTime time.Time
const ctLayout = "2006-01-02 15:04:05 Z07:00"
// UnmarshalJSON Parses the json string in the custom format
func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) {
@lummie
lummie / enum.go
Last active May 2, 2024 13:13
Golang Enum pattern that can be serialized to json
package enum_example
import (
"bytes"
"encoding/json"
)
// TaskState represents the state of task, moving through Created, Running then Finished or Errorred
type TaskState int