英文:
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/aaa
和curl -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-encoded
的POST
方法。
因此,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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论