http接口404是因为未调用registerxxxhandlerfromendpoint注册路由;该函数必须在http.listenandserve前显式调用,且ctx不可提前cancel、endpoint需指向已启动的grpc服务。

没调用 RegisterXXXHandlerFromEndpoint,HTTP 接口一定 404 —— 这不是配置问题,是根本没挂载路由。
为什么 HTTP 接口全返回 404?
gRPC-Gateway 不是中间件,它不会自动注册到 HTTP server 的路由树里。生成的 service.pb.gw.go 只是一堆 handler 函数,不显式调用注册函数,http.ServeMux 就完全不知道这些路径存在。
-
RegisterGreeterHandlerFromEndpoint(或你服务名对应的函数)必须在main()中调用,且要在http.ListenAndServe之前 - 传入的
ctx不能已 cancel:比如ctx, _ := context.WithTimeout(context.Background(), 100ms)后直接传入——注册过程可能超时失败,静默跳过 -
endpoint参数必须指向一个**已启动、可连通**的 gRPC server,例如"localhost:9090";写成"127.0.0.1:9090"在某些 TLS 或 DNS 配置下会解析失败 - 别把
runtime.NewServeMux()塞进 Gin/Echo 的某个路由里(如r.POST("/v1/hello", mux.ServeHTTP)),这会绕过 gateway 内部的 method/path 匹配逻辑,导致 query 参数丢失、body 解析失败
proto 注解写了但 curl 仍 404?检查三个硬性条件
HTTP 映射注解(如 post: "/v1/hello")只是声明,不是魔法。它生效需要工具链完整、路径正确、生成动作到位。
-
import "google/api/annotations.proto"和import "google/api/http.proto"必须存在,且protoc -I能找到它们 —— 通常要加-I $GOPATH/pkg/mod/github.com/grpc-ecosystem/grpc-gateway/v2@latest/third_party/googleapis -
protoc命令必须显式包含--grpc-gateway_out参数,例如:protoc --grpc-gateway_out=logtostderr=true:. service.proto;漏掉这步,service.pb.gw.go根本不会生成 - 路径变量(如
get: "/v1/hello/{name}")能自动绑定字段,但 query 参数(如?limit=10)必须在 proto 中显式声明为字段,并设body: "*"或绑定到具体字段,否则 gateway 不解析也不透传
能不能让 gRPC 和 HTTP 共享一个端口?
能,但不是“两个 ListenAndServe 绑同一个端口”那么简单 —— 那会直接报 address already in use 或随机 503。
- 真正可行的是用
http.Server.Handler做协议分发:HTTP/1.1 流量交给 gateway 的runtime.ServeMux,HTTP/2 流量交给 gRPC server - 推荐用
golang.org/x/net/http2+h2c.NewHandler包裹 gRPC server,并 fallback 到 gateway mux;不要自己手写协议嗅探逻辑(容易漏掉 h2c upgrade 头或误判) - 共享端口意味着共用同一套 TLS 配置、超时、CORS、gzip 等中间件,需统一在
http.Server层处理,而不是分别套在 gateway 和 grpc server 上
最常被忽略的其实是 ctx 生命周期和 endpoint 的连通性验证 —— 很多人在本地跑通后部署到 Kubernetes 就 404,往往是因为 endpoint 写了 localhost:9090,而 gateway 和 grpc server 在不同 Pod 里,根本连不通。
golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!











