Advanced routing
In the next section of this book we’re going to add a HTML form to our application so that users can create new snippets.
To make this work smoothly, we’ll first need to update our application routes so that requests to /snippet/create
are handled differently based on the request method. Specifically:
- For
GET /snippet/create
requests we want to show the user the HTML form for adding a new snippet. - For
POST /snippet/create
requests we want to process this form data and then insert a newsnippet
record into our database.
While we’re at it, there are a couple of other routing-related improvements that we’ll also make:
- We’ll restrict all our other routes — which simply return information — to only support
GET
requests. - We’ll use clean URLs so that any variables are included in the URL path (like
/snippet/view/123
) and not appended as a query string (like/snippet/view?id=123
).
Essentially, we want to rejig our application routes and handlers so that they end up looking like this:
Method | Pattern | Handler | Action |
---|---|---|---|
GET | / | home | Display the home page |
GET | /snippet/view/:id | snippetView | Display a specific snippet |
GET | /snippet/create | snippetCreate | Display a HTML form for creating a new snippet |
POST | /snippet/create | snippetCreatePost | Create a new snippet |
GET | /static/ | http.FileServer | Serve a specific static file |
As I mentioned earlier in the book, Go’s servemux doesn’t support method based routing or clean URLs with variables in them. There are some tricks you can use to get around this, but most people tend to decide that it’s easier to reach for a third-party package to help with routing.
In this section of the book we will:
- Briefly discuss the features of a few good third-party routers.
- Update our application to use one of these routers and demonstrate how to use method-based routing and clean URLs.