【发布时间】:2018-01-29 20:18:37
【问题描述】:
我编写了一个要求所有响应都是 JSON 的 REST API 服务。但是,当 Go HTTP 请求解析器遇到错误时,它会以纯文本响应的形式返回 400,而无需调用我的处理程序。示例:
> curl -i -H 'Authorization: Basic hi
there' 'http://localhost:8080/test' -v
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /test HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
> Authorization: Basic hi
> there
>
< HTTP/1.1 400 Bad Request
HTTP/1.1 400 Bad Request
< Content-Type: text/plain; charset=utf-8
Content-Type: text/plain; charset=utf-8
< Connection: close
Connection: close
<
* Closing connection 0
注意无效的授权标头。当然 400 是正确的响应,但它当然是文本/纯文本。有什么方法可以配置 Go http 解析器以使用自定义错误响应媒体类型和正文?
【问题讨论】:
-
你在使用某种框架吗?我从未在 stdlib http 处理程序中看到过这种行为。
标签: http go error-handling bad-request media-type