As a web developer you probably already know that HTML forms only support the GET and POST HTTP methods.
The de-facto workaround — which you might be familiar with if you've used frameworks like Ruby on Rails, Laravel or Express — is to include a hidden _method input in your form containing the spoofed HTTP method. A bit like this:
Another common workaround is to send a spoofed HTTP method in a X-HTTP-Method-Override header.
So how can we support these things in a Go application?
Intercepting and dealing with spoofed HTTP methods is the perfect task for some custom middleware. We want the middleware to:
Intercept POST requests before they reach any application handlers.
Check for a spoofed HTTP method, either in a _method parameter of the request body or a X-HTTP-Method-Override header.
If a spoofed method exists — and is equal to "PUT", "PATCH" or "DELETE" — the current http.Request.Method value should be updated accordingly.
It's pretty quick to implement:
You can then use the middleware in your application like so:
All code snippets in this post are free to use under the MIT Licence.
Not sure how to structure your Go web application? My new book guides you step-by-step through building a clear, idiomatic and secure real-world web application. Take a look!