123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package serverImpl
- import (
- "../example"
- "context"
- "fmt"
- "git.wanpinghui.com/WPH/go_common/wph"
- "google.golang.org/grpc"
- "google.golang.org/grpc/reflection"
- "log"
- "net"
- "net/http"
- "os"
- "os/signal"
- "syscall"
- "time"
- )
- // 服务端方法实现,没有什么不一样,正常实现即可。此示例只是为了看得更清楚,实例化的时候存了一下端口号,返回值中再把它带上
- type ExampleServer struct {
- addr string
- }
- func (s *ExampleServer) DoFormat(ctx context.Context, req *example.Data) (out *example.Data, err error) {
- var ipStr string
- ip, err := wph.PrivateIPv4()
- if nil == err && nil != ip {
- ipStr = ip.String()
- }
- return &example.Data{Text: fmt.Sprintf("%s (from %s%s)", req.Text, ipStr, s.addr)}, nil
- }
- func StartServer(addr string) {
- lis, err := net.Listen("tcp", addr)
- if err != nil {
- log.Fatalf("failed to listen: %v", err)
- }
- s := grpc.NewServer()
- example.RegisterFormatDataServer(s, &ExampleServer{addr: addr})
- // 注册到reflection,才能用grpcurl客户端测试
- reflection.Register(s)
- log.Printf("serving on %s\n", addr)
- if err := s.Serve(lis); err != nil {
- log.Fatalf("failed to serve: %v", err)
- }
- }
- func SignalHandler(httpServer *http.Server) {
- var (
- c chan os.Signal
- s os.Signal
- )
- c = make(chan os.Signal, 1)
- signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
- for {
- s = <-c
- switch s {
- case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- println("Shutdown http server")
- if err := httpServer.Shutdown(ctx); err != nil {
- println("http server failed to shutdown", err.Error())
- }
- cancel()
- println("Server exited")
- return
- default:
- return
- }
- }
- }
|