Skip to content

Instantly share code, notes, and snippets.

@sudaraka94
Created June 20, 2020 10:32
Show Gist options
  • Save sudaraka94/9c8aaed04199e694d3921bfdfabca610 to your computer and use it in GitHub Desktop.
Save sudaraka94/9c8aaed04199e694d3921bfdfabca610 to your computer and use it in GitHub Desktop.
Initializing db connections, loggers etc in a go serverless function
var (
db *sql.DB
logger *logging.Logger
once sync.Once
)
// This pattern is used to make the init function easily replaceable in tests
var initFunc = defaultInitFunc
func F(w http.ResponseWriter, r *http.Request) {
once.Do(func() {
// This will make sure that the initFunc will only run once after a teardown
if err := initFunc(); err != nil {
panic(err)
}
})
// Function logic goes here
}
func defaultInitFunc() error {
//Do the initializations like connecting to the db, initializing logger here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment