为什么 Golang 的 grpc-gateway 的 GET 路由会匹配 POST 请求?

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

Why Golang grpc-gateway's GET route matches POST request?

问题

我发现一个“get”路由可以匹配HTTP GET和HTTP POST请求。例如:

rpc aaa(User) returns (User) {
  option (google.api.http) = {
  get: "/api/v1/aaa"
};

它可以匹配curl -v -X GET -k https://127.0.0.1/api/v1/aaacurl -v -X POST -k https://127.0.0.1/api/v1/aaa

我想知道是否有可能严格匹配所有包括方法的路由?

英文:

I found a "get" route will match both HTTP GET and HTTP POST requests.
For example:

rpc aaa(User) returns (User) {
  option (google.api.http) = {
  get: "/api/v1/aaa"
};

It matches both curl -v -X GET -k https://127.0.0.1/api/v1/aaa and curl -v -X POST -k https://127.0.0.1/api/v1/aaa.

I was wondering if it's possible to strictly match all routes including methods?

答案1

得分: 1

简短回答

这是因为您没有指定请求的内容类型。

长篇回答

根据规范,您可以将您的GET请求编码为带有Content-Type: application/x-www-url-encodedPOST方法。

因此,grpc-gateway中的请求路由表在您的请求的Content-Type为application/x-www-url-encoded时尝试从POST方法回退到GET方法。

参考:
https://groups.google.com/d/msg/grpc-io/Xqx80hG0D44/1gwmwBcnNScJ
> "(注意) URL有长度限制(go/longer-urls)。某些浏览器和代理服务器会强制执行此限制。如果您的GET请求超过了限制,浏览器可能会拒绝发送它们。您可以改为使用带有内容类型application/x-www-form-urlencoded的POST请求。如果POST + URL已经映射到另一个后端函数,您应该添加"X-HTTP-Method-Override: GET"头来覆盖HTTP方法并获得正确的映射。

英文:

Short answer

It is because you did not specify the content-type of the request.

Long answer

By spec, it is allowed for you to encode your GET request into a POST method with Content-Type: application/x-www-url-encoded.

So the request routing table in grpc-gateway tries to fallback from POST method to GET when the Content-Type of your request is application/x-www-url-encoded.

ref.
https://groups.google.com/d/msg/grpc-io/Xqx80hG0D44/1gwmwBcnNScJ
> "(Note) URL has a length limitation (go/longer-urls). It's enfoced by some browsers and proxies. If your GET request exceeds the limitation, browser may reject to send them. You may change to use a POST request with content type application/x-www-form-urlencoded instead. If the POST + URL is already been mapped to another backend function, you shall add "X-HTTP-Method-Override: GET" header to override the HTTP method and obtain the correct mapping.

huangapple
  • 本文由 发表于 2017年8月27日 11:18:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/45901389.html
匿名

发表评论

匿名网友

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

确定