Not sure how to structure your Go web application?
My new book guides you through the start-to-finish build of a real world web application in Go — covering topics like how to structure your code, manage dependencies, create dynamic database-driven pages, and how to authenticate and authorize users securely.
As a web developer you probably already know that HTML forms only support the GET and POST HTTP methods.
If you want to send a PUT, PATCH or DELETE request from your web application, you need to either send a XMLHttpRequest from JavaScript (where they are supported by most major browsers) or implement a workaround in your server-side application code to support 'spoofed' or 'overridden' 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?
MethodOverride Middleware
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:
If you enjoyed this article, you might like to check out my recommended tutorials list or check out my books Let's Go and Let's Go Further, which teach you everything you need to know about how to build professional production-ready web applications and APIs with Go.