使用julienschmidt httprouter简化重复的错误处理

huangapple go评论74阅读模式
英文:

Simplifying repetitive error handling with julienschmidt httprouter

问题

Golang.org有一篇关于如何做到这一点的博文:
http://blog.golang.org/error-handling-and-go

他们基本上创建了一个新类型:

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

它实现了http.Handler接口,代码如下:

func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if err := fn(w, r); err != nil {
        http.Error(w, err.Error(), 500)
    }
}

通过这种方式,你可以在handleFunc中返回错误,这非常方便。

但是我正在使用julienschmidt httprouter,它使用的是一个函数,而不是实现了http.Handler接口的类型。我喜欢使用这个路由器,因为它支持命名参数。

我该如何包装httprouter.Handler函数,以便我可以返回错误和其他内容?

有没有一种方法可以避免重复的错误处理?我找不到方法。

英文:

Golang.org has a blogpost about how to do this:
http://blog.golang.org/error-handling-and-go

They basically make a new type

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

Which implements the http.Handler interface like so

func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if err := fn(w, r); err != nil {
        http.Error(w, err.Error(), 500)
    }
}

And with this you are able to return errors on your handleFunc which is great.

But I am using the julienschmidt httprouter and that uses a function rather than an interface that implements http.Handler. I like to use this router because it supports named parameters.

How can I wrap "something" around the httprouter.Handler function so that I can return errors and return other stuff aswel?

Is there a way to do this to prevent repetitive error handling? I could not find a way.

答案1

得分: 5

使用闭包:

type Handle func(http.ResponseWriter, *http.Request, Params)

type ErrHandle func(http.ResponseWriter, *http.Request, Params) error

func (eh ErrHandle) ToHandle() Handle {
	return func(w http.ResponseWriter, r *http.Request, p Params) {
		if err := eh(w, r, p); err != nil {
			http.Error(w, err.Error(), 500)
		}
	}
}

使用闭包的示例代码定义了两个类型:HandleErrHandleHandle 是一个函数类型,接受 http.ResponseWriter*http.RequestParams 作为参数。ErrHandle 是一个函数类型,接受相同的参数,并返回一个 error

ErrHandle 类型定义了一个方法 ToHandle(),该方法将 ErrHandle 转换为 Handle。转换后的 Handle 函数在执行时,会先调用原始的 ErrHandle 函数,如果返回的错误不为空,则会将错误信息返回给客户端,并设置状态码为 500。

英文:

Use closures:

type Handle func(http.ResponseWriter, *http.Request, Params)

type ErrHandle func(http.ResponseWriter, *http.Request, Params) error

func (eh ErrHandle) ToHandle() Handle {
	return func(w http.ResponseWriter, r *http.Request, p Params) {
		if err := eh(w, r, p); err != nil {
			http.Error(w, err.Error(), 500)
		}
	}
}

huangapple
  • 本文由 发表于 2015年9月10日 00:38:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/32485021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定