我已经编写了一个REST API服务,要求所有响应都是JSON。但是,当Go http请求解析器遇到错误时,它将以纯文本响应的形式返回400,而不会调用我的处理程序。例如:如何为解析错误定制Golang 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处理程序的这种行为。 – Adrian
没有。这里有一个[愚蠢的简单例子](https://play.golang.org/p/5iOUCklUeH)。 – theory