如何在Golang中使用”422 Unprocessable Entity (WebDAV)”或其他自定义的HTTP状态码?

huangapple go评论124阅读模式
英文:

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中实现。我看到的选项有:

  1. 编辑http包的源代码并添加自定义状态码。这样做很容易,但修改核心库可能不是一个好主意。

  2. 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

  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?

答案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

huangapple
  • 本文由 发表于 2013年12月12日 23:48:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/20547945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定