Go统一错误处理

main.go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
"go_dev/day11/example1/filelist"
"net/http"
"os"
)

type appHandle func(http.ResponseWriter, *http.Request) error

// 定义一个包装类型 对出错进行统一处理
func appWrap(hand appHandle) func(http.ResponseWriter, *http.Request) {

return func(resp http.ResponseWriter, req *http.Request) {
// 对panic进行处理
defer func() {
r := recover()
if r != nil {
http.Error(resp, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()

err := hand(resp, req)
if err != nil {
switch {
case os.IsNotExist(err):
http.Error(resp, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
}
}
}

func main() {

http.HandleFunc("/list/", appWrap(filelist.HandlerFile))

err := http.ListenAndServe(":8888", nil)
if err != nil {
return
}
}

handlerFile.go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package filelist

import (
"fmt"
"io/ioutil"
"net/http"
"os"
)

func HandlerFile(resp http.ResponseWriter, req *http.Request) error {
path := req.URL.Path[len("/list/"):]
fmt.Println("HandlerFile:", path)
file, err := os.Open(path)
if err != nil {
return err
}

all, err := ioutil.ReadAll(file)
if err != nil {
return err
}
resp.Write(all)
return nil
}