根目录为/server
1、创建yaml文件放在trip.proto文件同级目录下
/server/protp/trip.yaml
type: google.api.Service
config_version: 3
http:
rules:
- selector: coolcar.TripService.GetTrip
get: /trip/{id}
2、运行下方两条命令
在/server/protp目录中执行
protoc --go_out=plugins=grpc,paths=source_relative:gen/go trip.proto
protoc --grpc-gateway_out=paths=source_relative,grpc_api_configuration=trip.yaml:gen/go trip.proto
命令运行完成之后,会在gen/go中多一个trip.pb.gw.go文件
3、开启一个GRPC Gateway代理
/server/main.go
package main
import (
"context"
trippb "coolcar/proto/gen/go"
trip "coolcar/tripservice"
"fmt"
"log"
"net"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc"
)
func main() {
log.SetFlags(log.Lshortfile)
fmt.Println("service is runing")
go startGRPCGateway()
lis, err := net.Listen("tcp", ":8081")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
trippb.RegisterTripServiceServer(s, &trip.Service{})
log.Fatal(s.Serve(lis))
}
func startGRPCGateway() {
c := context.Background()
c, cancel := context.WithCancel(c)
defer cancel()
mux := runtime.NewServeMux()
err := trippb.RegisterTripServiceHandlerFromEndpoint(
c,
mux,
"localhost:8081",
[]grpc.DialOption{grpc.WithInsecure()},
)
if err != nil {
log.Fatalf("cannot start grpc gateway: %v", err)
}
err = http.ListenAndServe(":8080", mux)
if err != nil {
log.Fatalf("cannot listen and server: %v", err)
}
}
4、测试
将服务在命令行开启
访问测试