GolangNote

Golang笔记

goji 自定义错误函数,如404、500等

Permalink

goji 自定义错误函数,如404、500等

goji 自定义错误函数

Go: goji custom handle
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 输出:

plaintext: output
1
Internal Error (request ID: Vostro-260/t0hR4pQ0Ld-000002)

本文网址: https://golangnote.com/topic/58.html 转摘请注明来源

Related articles

关掉goji 的log 输出

goji 默认对每个请求都输出请求时间,在项目刚起步时可以作为性能参考,但在实际生产环境里,可以关掉log...

Write a Comment to "goji 自定义错误函数,如404、500等"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms