goji 自定义错误函数,如404、500等
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
43
44
45
46
47
48
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
"github.com/zenazn/goji/web/middleware"
)
func main() {
goji.Get("/", Root)
flag.Set("bind", ":8000")
goji.Serve()
}
type Hello struct {
Message string
}
func Root(c web.C, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
i := 0
if i == 0 {
ErrorString(c, w, 500, "test 500")
return
}
hello := &Hello{Message: "Hello, world"}
encoder := json.NewEncoder(w)
encoder.Encode(hello)
}
func ErrorString(c web.C, w http.ResponseWriter, code int, str string) {
c.Env["err"] = str
if code >= 500 {
errStr := fmt.Sprintf("Internal Error (request ID: %s)", middleware.GetReqID(c))
http.Error(w, errStr, code)
} else {
http.Error(w, str, code)
}
}
运行访问url 输出:
1
Internal Error (request ID: Vostro-260/t0hR4pQ0Ld-000002)
本文网址: https://golangnote.com/topic/58.html 转摘请注明来源