dubbo.apache.org/dubbo-go/v3@v3.1.1/protocol/grpc/internal/helloworld/server.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package helloworld
    19  
    20  import (
    21  	"context"
    22  	"net"
    23  )
    24  
    25  import (
    26  	log "github.com/dubbogo/gost/log/logger"
    27  
    28  	"google.golang.org/grpc"
    29  )
    30  
    31  // server is used to implement helloworld.GreeterServer.
    32  type server struct {
    33  	*GreeterProviderBase
    34  }
    35  
    36  func NewService() *server {
    37  	return &server{
    38  		GreeterProviderBase: &GreeterProviderBase{},
    39  	}
    40  }
    41  
    42  // SayHello implements helloworld.GreeterServer
    43  func (s *server) SayHello(ctx context.Context, in *HelloRequest) (*HelloReply, error) {
    44  	log.Infof("Received: %v", in.GetName())
    45  	return &HelloReply{Message: "Hello " + in.GetName()}, nil
    46  }
    47  
    48  func (s *server) Reference() string {
    49  	return "GrpcGreeterImpl"
    50  }
    51  
    52  type Server struct {
    53  	listener net.Listener
    54  	server   *grpc.Server
    55  }
    56  
    57  func NewServer(address string) (*Server, error) {
    58  	listener, err := net.Listen("tcp", address)
    59  	if err != nil {
    60  		return nil, err
    61  	}
    62  
    63  	server := grpc.NewServer()
    64  	service := NewService()
    65  	RegisterGreeterServer(server, service)
    66  
    67  	s := Server{
    68  		listener: listener,
    69  		server:   server,
    70  	}
    71  	return &s, nil
    72  }
    73  
    74  func (s *Server) Start() {
    75  	if err := s.server.Serve(s.listener); err != nil {
    76  		log.Fatalf("failed to serve: %v", err)
    77  	}
    78  }
    79  
    80  func (s *Server) Stop() {
    81  	s.server.GracefulStop()
    82  }