设置grpc-gateway的请求允许的内容类型
时间:2024-03-13
浏览:133
作者:佚名
有志者,事竟成!如果你在学习Golang,那么本文《设置grpc-gateway的请求允许的内容类型》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
我在同一个 go 应用程序中使用 grpc-gateway 来代理将 HTTP 转换为 GRPC。据我所知,默认情况下 grpc-gateway 为所有 RPC(包括流式传输)设置应用程序 application/json 格式。
所以,我的任务是:
- 传入的 HTTP 请求必须始终为
Content-type:application/json,否则请求应被拒绝并根据 RFC 发送 406。 - 传入的 HTTP 请求可能具有为一元 RPC 设置的
Accept: application/x-ndjson和为服务器流设置的Accept: applcation/x-ndjson标头。如果不满足406条件,则应返回。 - 传出 HTTP 请求必须设置
Content-type:applicaiton/json(对于简单的一元 RPC)和Content-type:application/x-ndjson对于服务器流。
因此,grpc-gateway 建议仅为 application/x-ndjson 设置自定义编组器,这实际上与默认编组器的作用相同,因此只需覆盖 ContentType 方法即可。这种方法不允许我为每个方法调用设置封送拆收器,并且不允许我拒绝每个请求不支持的内容类型。
如何仍然使用 grpc-gateway 来实现此目的?或者我应该考虑手动实现http grpc转换?
正确答案
我建议您不要使用 grpc-gateway 或任何其他工具将 grpc 转换为 http rpc。您正在给您的应用程序添加不必要的复杂性。
如果您有 grpc 服务,但无论出于何种原因,您的客户端无法调用 grpc,并且您需要通过纯 http 选项提供服务...是您的情况吗?
如果是您的情况,正确的方法是提供 http rpc 服务,并从中调用 grpc 服务。
http rpc 比 rest 简单得多,您不需要任何工具。
我在 golang 中实现了这个确切的案例 here
// creates a new book.
func (h bookstoreservice) createbook(w http.responsewriter, r *http.request) {
request := &bookv1.createbookrequest{}
proxy := httputil.getproxy(w, r, request)
proxy.setservicerequest(func(request proto.message) (proto.message, error) {
return h.client.createbook(r.context(), request.(*bookv1.createbookrequest))
})
proxy.call()
}
代理结构
func GetProxy(w http.ResponseWriter, r *http.Request, request proto.Message) *ServiceProxy {
proxy := &ServiceProxy{}
proxy.SetResponseWriter(w)
proxy.SetSourceRequest(r)
proxy.SetDestRequest(request)
return proxy
}
type ServiceProxy struct {
err error
serviceRequest func(request proto.Message) (proto.Message, error)
writer http.ResponseWriter
destRequest proto.Message
sourceRequest *http.Request
}
func (b *ServiceProxy) SetDestRequest(request proto.Message) {
b.destRequest = request
}
func (b *ServiceProxy) SetSourceRequest(request *http.Request) {
b.sourceRequest = request
}
func (b *ServiceProxy) SetServiceRequest(svcRequest func(request proto.Message) (proto.Message, error)) *ServiceProxy {
b.serviceRequest = svcRequest
return b
}
func (b *ServiceProxy) Call() {
b.writer.Header().Set("Content-Type", "application/json; charset=utf-8")
err := unmarshal(b.writer, b.sourceRequest, b.destRequest)
if err != nil {
return
}
resp, err := b.serviceRequest(b.destRequest)
if err != nil {
handleErrorResp(b.writer, err)
return
}
b.writer.WriteHeader(http.StatusOK)
json.NewEncoder(b.writer).Encode(resp)
}
func (b *ServiceProxy) SetResponseWriter(w http.ResponseWriter) {
b.writer = w
}今天关于《设置grpc-gateway的请求允许的内容类型》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
