Last active
April 29, 2019 15:15
-
-
Save wtask/32b5bf8ba8555a7e3a43c3dd82447e11 to your computer and use it in GitHub Desktop.
Golang: simplest way to execute several deferred funcs and return appropriate exit code from main
This file contains hidden or 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
package main | |
import ( | |
"some/logging" | |
"also/database" | |
"finally/application" | |
"fmt" | |
"os" | |
) | |
func main() { | |
// prepare exit code, first | |
exitCode := 0 | |
defer func(){ os.Exit(exitCode) }() | |
// make your initialization | |
logger, err := logging.NewFileLog("filename") | |
if err != nil { | |
fmt.Println(err) | |
exitCode = 1 | |
return | |
} | |
defer logger.Close() | |
db, err := database.Open() // in real app your will need some arguments for open | |
if err = nil { | |
logger.Errorf("Can't open database: %v", err) | |
exitCode = 1 | |
return | |
} | |
defer db.Close() | |
// start your app | |
app, err := application.New(db, logger) | |
if err != nil { | |
logger.Errorf("Can't start application: %v", err) | |
exitCode = 1 | |
return | |
} | |
logger.Info("Started...") | |
if err = app.Run(); err != nil { | |
logger.Errorf("Stopped with error: %v", err) | |
exitCode = 2 | |
return | |
} | |
logger.Info("Done") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment