当前位置:网站首页>Grc: GRC interface is mixed with restful API

Grc: GRC interface is mixed with restful API

2022-06-24 02:37:00 Trespass

Introduce

This article will show you how to gRPC Mixed use in microservices Restful API.

Here we are not referring to gRPC Interface to Restful API, But let different gRPC Interface and Restful API coexistence .

grpc-gateway This feature is already supported .

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

Please visit the following address for a complete tutorial :

install

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

Quick start

In this case , Will not write any gRPC Interface , We will be in gRPC Add an independent... To the service Restful API.

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

stay grpc-gateway Create a GET /custom Method .

adopt boot.GetGrpcEntry("greeter").GwMux.HandlePath() Method to add a custom interface . For example, file upload .

package main

import (
	"context"
	"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)
    
	// !!!!!!
	// This codes should be located after Bootstrap()
	grpcEntry.GwMux.HandlePath("GET", "/custom", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
		w.Write([]byte("Custom routes!"))
	})

	// Wait for shutdown sig
	boot.WaitForShutdownSig(context.Background())
}

3. verification

$ curl "localhost:8080/custom"
Custom routes!
原网站

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