当前位置:网站首页>Grpc: how to implement the restful API for file uploading?

Grpc: how to implement the restful API for file uploading?

2022-06-24 03:06:00 Trespass

Introduce

This article will show you how to gRPC File upload in microservice Restful API?

Why do you need such an article ?

gRPC We can go through Streaming To transfer large files to each other , But by grpc-gateway on gRPC We can't achieve . therefore , Need to bypass gRPC Directly in grpc-gateway Add API.

We will use rk-boot To start up gRPC service .

Please visit the following address for a complete tutorial :https://rkdev.info/cnhttps://rkdocs.netlify.app/cn ( spare )

install

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

Quick start

rk-boot Integrated by default grpc-gateway, And will start by default .

1. establish boot.yaml

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

2. establish main.go

Be careful ,grpcEntry.GwMux.HandlePath() Be sure to write boot.Bootstrap() after , Otherwise Panic.

package main

import (
	"context"
	"fmt"
	"github.com/rookie-ninja/rk-boot"
	"github.com/rookie-ninja/rk-grpc/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.GetEntry("greeter").(*rkgrpc.GrpcEntry)

	// 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. verification

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

版权声明
本文为[Trespass ]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/10/20211019035502526k.html