This amazing article here: https://www.alexedwards.net/blog/how-to-properly-parse-a-json-request-body explains very well how to write a Golang handler.
I need to use two handlers, one after the other, only if the first one gives error.
Like this:
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)
}
Is there a different method instead of reading twice or more the same
request.Body
?Is there a way to avoid writing all that code in the article (which needs to be maintained) and using open source libraries that do it better and are revised by thousands of smarter eyes than mine?
E.G.: Can I use a
go-chi
method?