I was thinking of ways to do routing with the standard library. Is it valid to have a handler function that will call other handler functions depending on the request type? e.g.
func main() {
m := http.NewServeMux()
m.HandleFunc("/books", books)
// ...
}
func books(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
getBooks(w, r)
case "POST":
createBook(w, r)
}
}
Is this good practice? I didn't want to declare a custom handler since I find functions to be a bit cleaner.
By using app.route() method, we can create chainable route handlers for a route path in Express.js.
The arguments available to an Express. js route handler function are: req - the request object. res - the response object.
Route handlers are the blocks of code that handle logic for your routes. This can be in the form of a function, an array of functions, or combinations of both. In the route handlers that we've created so far in this course, we've kept them fairly simple with a single callback.
Yes, this is perfectly valid; handlers are just functions so there is no reason it shouldn't be. In fact, this is how middleware is usually implemented.
There is nothing "magic" about handler functions at all. As long as you're writing to the correct file descriptor (w http.ResponseWriter
) anything goes.
That doesn't mean that using this pattern is necessarily a good idea for all applications – routing libraries exist for a reason – but for smaller programs it will work just fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With