x/tools/gopls: add "if err != nil" snippet completion for net/http's HandlerFunc #48487
Description
The net/http HandlerFunc is a very common function that Go developers write:
func handler(w http.ResponseWriter, r *http.Request)
Since the function doesn't return any errors, most users will have to handle the error in the following way:
func handler(w http.ResponseWriter, r *http.Request) {
results, err := doSomething()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// use results
}
This can be quite tedious to write and people (aka me) often forget to add the "return" statement which ends up causing the net/http library to spit out errors about multiple status codes being written to the same response.
In production applications, Go developers typically structure their http servers in a way that will minimize the amount they have to do the HTTP error handling above. But they most likely still have to do it once per handler, or sometimes they want to prototype a server quickly without having to think about how to nicely structure their code to DRY up the error handling logic.
Therefore, as a continuation of improvements to our snippet completions mentioned in 43310, I'd love to add a completion that will simply offer to write the above error handling snippet for you. It should also put placeholders on the error and status code arguments while picking sane defaults such as err.Error()
and http.StatusInternalServerError
.
Since the code structure for snippet completions is already in place, adding this use case should be a minimal change. I've included a CL to show the type of change needed, which can be reviewed/merged if this issue is accepted.
Thanks!