package main import ( "context" "fmt" "go_mod_testdemo/pb" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "net" ) type AdService struct { } func (this *AdService) GetBrandInfo(ctx context.Context, req *pb.GetBrandInfoReq) (*pb.GetBrandInfoRsp, error) { if req.BrandId == 10 { return &pb.GetBrandInfoRsp{BrandId: 10, BrandName: "ad"}, nil } return &pb.GetBrandInfoRsp{BrandId: req.BrandId, BrandName: "other"}, nil } func main() { // 0 读取 server 的证书 creds, err := credentials.NewServerTLSFromFile("cert/server.crt", "cert/server.key") if err != nil { fmt.Println("credentials NewServerTLSFromFile err: ", err) return } // 1 初始化 grpc 对象 grpcServer := grpc.NewServer(grpc.Creds(creds)) // 2 注册服务 pb.RegisterAdServiceServer(grpcServer, new(AdService)) // 3 创建监听 listener, err := net.Listen("tcp", "127.0.0.1:8080") if err != nil { fmt.Println("net Listen err: ", err) return } defer listener.Close() // 4 绑定服务 grpcServer.Serve(listener) }