dounieqi6959 2013-12-12 15:48
浏览 198
已采纳

如何在golang中使用“ 422无法处理的实体(WebDAV)”或任何其他自定义的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?

  • 写回答

2条回答 默认 最新

  • duanbarong4321 2016-07-10 16:28
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败