'How is use "422 Unprocessable Entity (WebDAV)" or any other custom http status code in golang

The go http package only supports the status code from RFC 2616. A lot of REST apis like github use 422 for bad input data. I would like to also do this, but I don't see a good way of doing this in go. The options I see are

  1. Edit the source code to the http package and add it. This would be easy to do but would be bad to edit a core library.

  2. The http.Response struct has Status as a string StatusCode as an int. I think I could just set them in the responsce, but the http.Handler only has a RespnseWriter interface. It might be possible to make a http.Transport that has a RoundTripper that correctly sets the Response. Even if it is possible this seem like it would be a hacky to some degree.

So what is the best way of adding a custom http status code to go, or is it just a bad idea?



Solution 1:[1]

As the status 422 Unprocessable Entity is a WebDAV extension, you can use the package golang.org/x/net/webdav and handle it correctly:

http.Error(w,
    webdav.StatusText(webdav.StatusUnprocessableEntity),
    webdav.StatusUnprocessableEntity)

Solution 2:[2]

You can plug the status code in manually as a parameter of of http.Error():

func Handler(w http.ResponseWriter, req *http.Request) {
    http.Error(w, "Some Response Text", 422)
    return
}

This will return status 422 and the response "Some Response Text"

Here is a link to this function in the docs.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cd1
Solution 2