这篇精彩的文章在这里:https : //www.alexedwards.net/blog/how-to-properly-parse-a-json-request-body 很好地解释了如何编写 Golang 处理程序。
我需要使用两个处理程序,一个接一个,只有当第一个出现错误时。
像这样:
func main() {
r := chi.NewRouter()
r.Post("/api", MyHandlers)
}
func MyHandlers(w http.ResponseWriter, r *http.Request) {
err := DoSomething(w, r)
if err != nil {
println("OMG! Error!")
DoSomethingWithThisOneInstead(w, r)
}
}
func DoSomething(w http.ResponseWriter, r *http.Request) error {
// here I need to read request's Body
// and I can use io.TeeReader()
// and I can use all the code in the amazing article example
// but I don't want to, because it's a lot of code to maintain
res, err := myLibrary.DoSomething(requestBody)
if err != nil {
return err
}
render.JSON(w, r, res) // go-chi "render" pkg
return nil
}
func DoSomethingWithThisOneInstead(w http.ResponseWriter, r *http.Request) {
// here I need to read request's Body again!
// and I can use all the code in the amazing article example
// but I don't want to, because it's a lot of code to maintain
anotherLibrary.DoSomethingElse.ServeHTTP(w, r)
}
是否有不同的方法而不是阅读两次或多次相同的内容
request.Body?有没有办法避免在文章中编写所有代码(需要维护)并使用做得更好并且被成千上万比我聪明的眼睛修改的开源库?
EG:我可以使用一种
go-chi方法吗?