Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using intermediate handler function to route requests

Tags:

go

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.

like image 798
Zachscs Avatar asked Jul 09 '18 20:07

Zachscs


People also ask

How is it possible to create Chainable route handlers for a route path in Express JS?

By using app.route() method, we can create chainable route handlers for a route path in Express.js.

Which function arguments are available to Express route handlers?

The arguments available to an Express. js route handler function are: req - the request object. res - the response object.

What is a route handler?

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.


1 Answers

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.

like image 63
Martin Tournoij Avatar answered Oct 09 '22 18:10

Martin Tournoij