Unfortunately, I don't think there's going to be an answer that you're happy with. At the end of the day the following must be true:
Each handler must use the http.Responsewriter
and *http.Request
to service the request.
A thing to keep in mind is that shorter and simpler do not always go hand-in-hand. Passing the writer and the response to the functions that need them, while slightly verbose, is exceedingly simple.
What may make you happiest is to instead push most of the logic actually down into some additional methods that deal in the semantics of the operations rather than the network request layer. Using a GET request to load a record as an example, you might instead structure it as:
func main() {
http.DefaultServeMux.HandleFunc("/", getHandler)
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
func getHandler(w http.ResponseWriter, r *http.Request) {
// Do stuff with the request, like deserialize
// Extract the ID
// Call getLogic
// return an appropriate error or serialize the response back out
}
func getLogic(recordID int) (Record, error) {
// Do actual interesting logic here.
}
Splitting it up like this is not without a potential cost in simplicity. While it does let you test chunks of your logic without needing to deal with a http.ResponseWriter
or http.Request
you now have to make a decision where to cut that seam. Doing so consistently might be awkward.
You could also try to take a different approaches like create a struct per request, put the writer and request on it, and then call the appropriate method, but I wouldn't recommend it:
func getHandler(w http.ResponseWriter, r *http.Request) {
SingleRequest{w, r}.Get()
}
type SingleRequest struct {
writer http.ResponseWriter
request *http.Request
}
func (s SingleRequest) Get() {
// Do logic here, but the method still has to access s.writer and s.request
}
Neither of these approaches offer much in terms of simplicity of brevity. What minor amounts of brevity they do yield is, in my opinion, at the cost of simplicity. The first approach, however, could be reasonable depending on the complexity of a given handler. It is, after all, the extension of the pattern of making smaller functions to break up a larger function.
As it stands currently, I am unaware of any approach that universally increases simplicity while decreasing code size. Instead, we should focus on why you feel like this is a problem that needs to be solved in the first place. Are you familiar with the httptest package in the standard lib? If testing is your concern it will help you with testing these handlers.