惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Blog of Author Tim Ferriss
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
云风的 BLOG
云风的 BLOG
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Palo Alto Networks Blog
D
Docker
H
Hackread – Cybersecurity News, Data Breaches, AI and More
S
Schneier on Security
Engineering at Meta
Engineering at Meta
I
InfoQ
L
LangChain Blog
Cyberwarzone
Cyberwarzone
T
Tenable Blog
WordPress大学
WordPress大学
P
Privacy & Cybersecurity Law Blog
罗磊的独立博客
Apple Machine Learning Research
Apple Machine Learning Research
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Jina AI
Jina AI
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
博客园 - 三生石上(FineUI控件)
酷 壳 – CoolShell
酷 壳 – CoolShell
Know Your Adversary
Know Your Adversary
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Last Watchdog
The Last Watchdog
Last Week in AI
Last Week in AI
Cloudbric
Cloudbric
S
SegmentFault 最新的问题
爱范儿
爱范儿
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 叶小钗
AI
AI
T
Tor Project blog
I
Intezer
T
Threatpost
www.infosecurity-magazine.com
www.infosecurity-magazine.com
V
Visual Studio Blog
N
News and Events Feed by Topic
Latest news
Latest news
S
Security Affairs
博客园 - Franky
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
B
Blog RSS Feed
C
Cybersecurity and Infrastructure Security Agency CISA
Hugging Face - Blog
Hugging Face - Blog
小众软件
小众软件
S
Securelist

博客园 - Mr__BRIGHT

Jupyter Notebook导入自定义模块时ImportError Pandas数据处理(2): 数据透视表,行转列、列转行、以及一行生成多行 Pandas数据处理(1): 基础方法整理 Win10-PowerShell使用conda activate激活环境无效问题及常用Conda操作 Spring AOP动态代理实现,解决Spring Boot中无法正常启用JDK动态代理的问题 CentOS常用的文件操作命令 win10周年更新后程序各种卡死,进程无法结束怎么破? GIT分支管理模型 - Mr__BRIGHT - 博客园 CentOS访问Windows共享文件夹的方法 GIT FLOW 时序图 - Mr__BRIGHT Hyper-v虚拟机文件VHDX与VHD的格式转换 CentOS详解top命令各个数据的含义 CentOS网络配置 git svn clone时间估算 使用git svn clone迁移svn仓库(保留提交记录) .NET 4.5+项目迁移.NET Core的问题记录 老毛桃u盘装系统制作工具 一位39岁程序员的困惑:知道得越多编程越慢怎么办? 程序员的回归式进化
Golang 如何统一处理HTTP请求中的异常捕获
Mr__BRIGHT · 2017-09-21 · via 博客园 - Mr__BRIGHT

最近写go,路由选择httprouter,现在希望在不修改httprouter源码的前提下,对所有注册的路由handle进行异常捕获。

golang使用panic()产生异常,然后可以recover()来捕获到异常,否则主程序直接宕掉,这是我们不希望看到的。
或者全程检查error,不主动抛出异常。即便这样,可能异常依然不能避免。

func RegRouters(r *httprouter.Router) {
	r.GET("/", Home)
	r.GET("/contact", Contact)
}

func Home(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	defer func() {
			if pr := recover(); pr != nil {
				fmt.Printf("panic recover: %v\r\n", pr)
				debug.PrintStack()
			}
		}()
	//something
}

func Contact(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	defer func() {
			if pr := recover(); pr != nil {
				fmt.Printf("panic recover: %v\r\n", pr)
				debug.PrintStack()
			}
		}()
	//something
}

正常的路由表长这样,在C#中相当于对每个请求加try...catch,将业务上代码包裹起来。
golang同理:

func RegRouters(r *httprouter.Router) {
	r.GET("/", WrapHandle(Home))
	r.GET("/contact", WrapHandle(Contact))
}

WrapHandle需要有一个handle类型的参数,同时返回值要能被httprouter接收

func WrapHandle(handle httprouter.Handle) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		defer func() {
			if pr := recover(); pr != nil {
				fmt.Printf("panic recover: %v\r\n", pr)
				debug.PrintStack()
			}
		}()
		handle(w, r, p)
	}
}

加一个上下文,把handle简化一下

func WrapHandle(handle func(ctx *context.Context)) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		defer func() {
			if pr := recover(); pr != nil {
				fmt.Println("panic recover: %v", pr)
				debug.PrintStack()
			}
		}()
		ctx := context.NewContext(w, r, p)
		handle(ctx)
	}
}
func Home(ctx *context.Context) {
	defer func() {
			if pr := recover(); pr != nil {
				fmt.Printf("panic recover: %v\r\n", pr)
				debug.PrintStack()
			}
		}()
	//something
}

func Contact(ctx *context.Context) {
	defer func() {
			if pr := recover(); pr != nil {
				fmt.Printf("panic recover: %v\r\n", pr)
				debug.PrintStack()
			}
		}()
	//something
	id = ctx.FormInt64("id") //通过context从FORM取值,并转换为int64
}

这里加了一个context包,handle的参数也减少到一个,主要是context上可以做更多的事情。

一个简单的请求上下文的原型:

type Context struct {
	responseWriter http.ResponseWriter
	request        *http.Request
	params         httprouter.Params
	Data           map[string]interface{}
}

func NewContext(w http.ResponseWriter, r *http.Request, params httprouter.Params) *Context {
	ctx := new(Context)
	ctx.responseWriter = w
	ctx.request = r
	ctx.params = params
	ctx.Data = make(map[string]interface{})
	return ctx
}

func (ctx *Context) FormValue(name string) string {
	return ctx.request.FormValue(name)
}

func (ctx *Context) FormInt64(name string) int64 {
	value, _ := strconv.ParseInt(ctx.FormValue(name), 10, 64)
	return value
}

//更多扩展....

好了,先到这里,希望对你有帮助。