英文:
How is use "422 Unprocessable Entity (WebDAV)" or any other custom http status code in golang
问题
go http包只支持RFC 2616中的状态码。很多像GitHub这样的REST API使用422表示输入数据错误。我也想这样做,但是我没有找到一个好的方法在go中实现。我看到的选项有:
-
编辑http包的源代码并添加自定义状态码。这样做很容易,但修改核心库可能不是一个好主意。
-
http.Response结构体有一个字符串类型的Status和一个整型的StatusCode。我认为我可以在响应中设置它们,但是http.Handler只有一个ResponseWriter接口。可能可以创建一个具有正确设置响应的RoundTripper的http.Transport。即使可能实现,这种方法似乎有些不太正规。
那么,在go中添加自定义http状态码的最佳方法是什么,或者这只是一个坏主意?
英文:
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
-
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.
-
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?
答案1
得分: 2
由于状态码422 Unprocessable Entity
是WebDAV的扩展,你可以使用golang.org/x/net/webdav
包来正确处理它:
http.Error(w,
webdav.StatusText(webdav.StatusUnprocessableEntity),
webdav.StatusUnprocessableEntity)
英文:
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)
答案2
得分: 0
你可以将状态码手动作为http.Error()
的参数插入:
func Handler(w http.ResponseWriter, req *http.Request) {
http.Error(w, "Some Response Text", 422)
return
}
这将返回状态码422和响应文本"Some Response Text"。
这里是该函数在文档中的链接。
英文:
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.
答案3
得分: 0
一些状态码,包括422,是在Go 1.7中添加的。
https://github.com/golang/go/commit/b9ec0024fbc18dd94eff7240afd82fac6b4d8fdc
英文:
A number of status codes including 422 were added in go 1.7
https://github.com/golang/go/commit/b9ec0024fbc18dd94eff7240afd82fac6b4d8fdc
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论