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

golang web 框架 goji 介绍

goji 是个后起的golang web框架,避免其它golang web 框架走过的坑,在性能、简单性方面做得很好。...

goji v2 与goji 的对接

goji 是个优秀的框架,作者说以前是弄着玩的,后来较正规的按照go 的设计原则来重构,不过尽量保持原来的接口。...

goji + SSDB 构建的应用

已经过了学生的年纪,学习新东西不那么快,尝试从python 转向golang,就从博客程序开始。...

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

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