Created
June 20, 2020 10:32
-
-
Save sudaraka94/9c8aaed04199e694d3921bfdfabca610 to your computer and use it in GitHub Desktop.
Initializing db connections, loggers etc in a go serverless function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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