错误处理
_, err := os.OpenFile(filename, os.O_EXCL|os.O_CREATE, 0666)
if err != nil {
if pahErr, ok := err.(*os.PathError); !ok {
panic(err)
}else{
fmt.Printf("%s %s %s\n",pahErr.Path,pahErr.Op,pahErr.Err)
}
return
}
统一实现任务处理
type appHandler func(w http.ResponseWriter, req *http.Request) error
// errWrapper 错误处理
func errWrapper(handler appHandler) func(http.ResponseWriter, *http.Request){
return func(w http.ResponseWriter, req *http.Request){
err := handler(w, req)
if err != nil {
code := http.StatusOK
switch {
case os.IsNotExist(err):
code = http.StatusNotFound
case os.IsPermission(err):
code = http.StatusForbidden
default:
code = http.StatusInternalServerError
}
http.Error(w, http.StatusText(code), code)
}
}
}
func HandleFileListing(w http.ResponseWriter, req *http.Request) error{
path := req.URL.Path[len("/list/"):]
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
all, err := ioutil.ReadAll(file)
if err != nil {
return err
}
w.Write(all)
return nil
}
panic兜底处理 recover
defer func(){
r := recover()
if err, ok := r.(error); ok {
fmt.Println(err)
} else {
panic(err)
}
}()