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
你还在原价购买阿里云、腾讯云、华为云、天翼云产品?那就亏大啦!现在申请成为四大品牌云厂商VIP用户,可以3折优惠价购买云服务器等云产品,并且可享四大云服务商产品终身VIP优惠价,还等什么?赶紧点击下面对应链接免费申请VIP客户吧:
相关文章
- Jgit的使用笔记
- 利用Github Action实现Tornadofx/JavaFx打包
- 叹息!GitHub Trending 即将成为历史!
- 微软软了?开源社区讨论炸锅,GitHub CEO 亲自来答
- GitHub Trending 列表频现重复项,前后端都没去重?
- Photoshop Elements 2021版本软件安装教程(mac+windows全版本都有)
- (ps全版本)Photoshop 2020的安装与破解教程(mac+windows全版本都有)
- (ps全版本)Photoshop cc2018的安装与破解教程(mac+windows全版本,包括2023
- 环境搭建:Oracle GoldenGate 大数据迁移到 Redshift/Flat file/Flume/Kafka测试流程
- 每个开发人员都要掌握的:最小 Linux 基础课
- 来撸羊毛了!Windows 环境下 Hexo 博客搭建,并部署到 GitHub Pages
- 超实用!手把手入门 MongoDB:这些坑点请一定远离
- 【GitHub日报】22-10-09 zustand、neovim、webtorrent、express 等4款App今日上新
- 【GitHub日报】22-10-10 brew、minio、vite、seaweedfs、dbeaver 等8款App今日上新
- 【GitHub日报】22-10-11 cobra、grafana、vue、ToolJet、redwood 等13款App今日上新
- Photoshop 2018 下载及安装教程(mac+windows全版本都有,包括最新的2023)
- Photoshop 2017 下载及安装教程(mac+windows全版本都有,包括最新的2023)
- Photoshop 2020 下载及安装教程(mac+windows全版本都有,包括最新的2023)
- Photoshop 2023 资源免费下载(mac+windows全版本都有,包括最新的2023)
- 最新版本Photoshop CC2018软件安装教程(mac+windows全版本都有,包括2023