Created
March 23, 2018 09:59
-
-
Save wjx0912/38516e3b6c43dcd4260d032185885dea to your computer and use it in GitHub Desktop.
golang use closure and wrap error
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
func listHandler(w http.ResponseWriter, r *http.Request) { | |
fileInfoArr, err := ioutil.ReadDir("./uploads") | |
check(err) | |
locals := make(map[string]interface{}) | |
images := []string{} | |
for _, fileInfo := range fileInfoArr { | |
images = append(images, fileInfo.Name) | |
} | |
locals["images"] = images | |
renderHtml(w, "list", locals) | |
} | |
func safeHandler(fn http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
defer func() { | |
if e, ok := recover().(error); ok { | |
http.Error(w, err.Error(), | |
http.StatusInternalServerError) | |
// out put custom 50x error page | |
// w.WriteHeader(http.StatusInternalServerError) | |
// renderHtml(w, "error", e) | |
// logging | |
log.Println("WARN: panic in %v. - %v", fn, e) | |
log.Println(string(debug.Stack())) | |
} | |
}() | |
fn(w, r) | |
} | |
} | |
func main() { | |
mux := http.NewServeMux() | |
staticDirHandler(mux, "/assets/", "./public", 0) | |
//mux.HandleFunc("/", listHandler) | |
mux.HandleFunc("/", safeHandler(listHandler)) | |
err := http.ListenAndServe(":8080", mux) | |
if err != nil { | |
log.Fatal("ListenAndServe: ", err.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment