在Go语言应用程序中的任何地方使用`ResponseWriter` – 中间件。

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

Use responsewriter anywhere in golang application - middleware

问题

我有一个相当复杂的单一端点,它运行了来自许多不同文件的算法。我正在使用文档中描述的http处理程序:

http.Handle("/foo", fooHandler)

http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

我想在出现错误时编写http响应,但不想在整个应用程序中将writer传递给深层的3个函数。我该如何编写一个中间件,允许我在应用程序的任何地方访问responsewriter并返回响应?

英文:

I have a single endpoint which is fairly complex and runs algorithms from quite a few different files. I'm using an http handler as described in the docs:

http.Handle("/foo", fooHandler)

http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

I want to write http responses in case of errors but don't want to have to pass the writer down 3 functions deep to achieve this. How would I write a middleware allowing me to access the responsewriter and return a response anywhere in the application?

答案1

得分: 3

只是为了总结一下我在评论中提到的内容,并加上一些额外的细节。

假设你的处理程序 H 调用了 F,F 又调用了 G,G 又调用了 J。

首选方法:不要ResponseWriter 一直传递到 F/G/J。相反,F、G、J 应该返回值,包括 error 用于表示错误,并且 H 应该构建响应并写入 ResponseWriter。这样可以使你的代码更模块化,更容易进行独立测试和重用。

可测试性很重要;假设你的函数 J 执行一些可能导致错误的计算。如果它只返回 error,那么测试就很简单 - 你只需要 J 的输入,然后可以断言在某些情况下得到了预期的错误。如果 J 不是返回一个 error,而是接受一个 ResponseWriter,那么你就需要创建一个假的 ResponseWriter,并验证正确的错误是否被写入其中。这就复杂得多了。

英文:

Just to summarize in an answer what I mentioned in the comment, with some additional details.

Let's say your handler H calls F, which calls G, which calls J.

Preferred approach: Don't pass a ResponseWriter all the way through to F/G/J. Instead, F, G, J should return values, including error for errors, and H should build up the response and write to a ResponseWriter. This makes your code more modular, easier to test in isolation and easier to reuse.

Testability is important; assume your function J does some computation which may result in an error. If it just returns error, this is trivial to test - all you need are J's inputs, and then you can assert that you get the expected errors in some scenarios. If instead of returning an error, J takes a ResponseWriter, you'll need to create a fake ResponseWriter and verify that the right errors get written into it. This is much more complicated.

huangapple
  • 本文由 发表于 2021年5月21日 21:57:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/67638302.html
匿名

发表评论

匿名网友

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

确定