zl程序教程

您现在的位置是:首页 >  其他

当前栏目

GRPC: 如何实现文件上传 Restful API ?

2023-02-26 10:16:19 时间

介绍

本文将介绍如何在 gRPC 微服务中实现文件上传 Restful API。

为什么需要这么一篇文章?

gRPC 里我们可以通过 Streaming 来互传大文件,不过通过 grpc-gateway on gRPC 我们是无法实现的。
因此,需要绕过 gRPC 直接在 grpc-gateway 中添加 API。

(福利推荐:阿里云、腾讯云、华为云服务器最新限时优惠活动,云服务器1核2G仅88元/年、2核4G仅698元/3年,点击这里立即抢购>>>

我们将会使用 rk-boot 来启动 gRPC 服务。

请访问如下地址获取完整教程:

安装

go get github.com/rookie-ninja/rk-boot

快速开始

rk-boot 默认集成了 grpc-gateway,并且会默认启动。

1.创建 boot.yaml

--- grpc:   - name: greeter                   # Name of grpc entry     port: 8080                      # Port of grpc entry     enabled: true                   # Enable grpc entry

2.创建 main.go

注意,grpcEntry.GwMux.HandlePath() 一定要写到 boot.Bootstrap() 之后,否则会出现 Panic。

package main  import (     "context"     "fmt"     "github.com/rookie-ninja/rk-boot"     "net/http" )  // Application entrance. func main() {     // Create a new boot instance.     boot := rkboot.NewBoot()      // Bootstrap     boot.Bootstrap(context.Background())      // Get grpc entry with name     grpcEntry := boot.GetGrpcEntry("greeter")      // Attachment upload from http/s handled manually     grpcEntry.GwMux.HandlePath("POST", "/v1/files", handleBinaryFileUpload)      // Wait for shutdown sig     boot.WaitForShutdownSig(context.Background()) }  func handleBinaryFileUpload(w http.ResponseWriter, req *http.Request, params map[string]string) {     err := req.ParseForm()     if err != nil {         http.Error(w, fmt.Sprintf("failed to parse form: %s", err.Error()), http.StatusBadRequest)         return     }      f, header, err := req.FormFile("attachment")     if err != nil {         http.Error(w, fmt.Sprintf("failed to get file 'attachment': %s", err.Error()), http.StatusBadRequest)         return     }     defer f.Close()      fmt.Println(header)      //     // Now do something with the io.Reader in `f`, i.e. read it into a buffer or stream it to a gRPC client side stream.     // Also `header` will contain the filename, size etc of the original file.     // }

3.验证

$ curl -X POST -F "[email protected]" localhost:8080/v1/files

GRPC: 如何实现文件上传 Restful API ?


本站部分内容转载自网络,版权属于原作者所有,如有异议请联系QQ153890879修改或删除,谢谢!
转载请注明原文链接:GRPC: 如何实现文件上传 Restful API ?

你还在原价购买阿里云、腾讯云、华为云、天翼云产品?那就亏大啦!现在申请成为四大品牌云厂商VIP用户,可以3折优惠价购买云服务器等云产品,并且可享四大云服务商产品终身VIP优惠价,还等什么?赶紧点击下面对应链接免费申请VIP客户吧:

1、点击这里立即申请成为腾讯云VIP客户

2、点击这里立即注册成为天翼云VIP客户

3、点击这里立即申请成为华为云VIP客户

4、点击这里立享阿里云产品终身VIP优惠价

喜欢 (0)
[[email protected]]
分享 (0)