Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money
introduce
This article will introduce how to realize file upload Restful API in gRPC microservice.
Why do you need such an article?
GRPC we can use Streaming to transfer large files to each other, but we can’t do this through grPC-gateway on gRPC. Therefore, you need to bypass gRPC and add the API directly to grPC-Gateway.
We will use RK-boot to start the gRPC service.
Please visit the following address for the full tutorial:
- rkdev.info/cn
- Rkdocs.net lilify. app/cn (standby)
The installation
go get github.com/rookie-ninja/rk-boot
Copy the code
Quick start
Rk-boot integrates grPC-gateway by default and starts by default.
1. Create the boot. Yaml
---
grpc:
- name: greeter # Name of grpc entry
port: 8080 # Port of grpc entry
enabled: true # Enable grpc entry
Copy the code
2. Create a main. Go
Note that grpcEntry. GwMux. HandlePath () must be written in the boot. The Bootstrap (), otherwise there will be a 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. // }Copy the code
3. Verify
$ curl -X POST -F "[email protected]" localhost:8080/v1/files
Copy the code