calls to log.Fatalf only in main() or init() functions
28func serveSearchResults() *httptest.Server {
29 searchResults, err := ioutil.ReadFile("./testFiles/searchResults.json")
30 if err != nil {
31 log.Fatalf("Error reading file: %s", err) 32 }
33
34 f := func(w http.ResponseWriter, r *http.Request) {
Description
Packages exposing functions that can stop program execution by exiting are hard to reuse. Program exits in functions other than main() or init() are not encouraged.
Bad practice
func nonMainFunc() {
safelyExit := true // somehow arrive at this value
if safelyExit {
os.Exit(0)
}
}
func main() {
nonMainFunc()
}
Recommended
func nonMainFunc() bool {
safelyExit := true // somehow arrive at this value
}
func main() {
safelyExit := nonMainFunc()
if safelyExit {
os.Exit(0)
}
}