example_server.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package serverImpl
  2. import (
  3. "../example"
  4. "context"
  5. "fmt"
  6. "git.wanpinghui.com/WPH/go_common/wph"
  7. "google.golang.org/grpc"
  8. "google.golang.org/grpc/reflection"
  9. "log"
  10. "net"
  11. "net/http"
  12. "os"
  13. "os/signal"
  14. "syscall"
  15. "time"
  16. )
  17. // 服务端方法实现,没有什么不一样,正常实现即可。此示例只是为了看得更清楚,实例化的时候存了一下端口号,返回值中再把它带上
  18. type ExampleServer struct {
  19. addr string
  20. }
  21. func (s *ExampleServer) DoFormat(ctx context.Context, req *example.Data) (out *example.Data, err error) {
  22. var ipStr string
  23. ip, err := wph.PrivateIPv4()
  24. if nil == err && nil != ip {
  25. ipStr = ip.String()
  26. }
  27. return &example.Data{Text: fmt.Sprintf("%s (from %s%s)", req.Text, ipStr, s.addr)}, nil
  28. }
  29. func StartServer(addr string) {
  30. lis, err := net.Listen("tcp", addr)
  31. if err != nil {
  32. log.Fatalf("failed to listen: %v", err)
  33. }
  34. s := grpc.NewServer()
  35. example.RegisterFormatDataServer(s, &ExampleServer{addr: addr})
  36. // 注册到reflection,才能用grpcurl客户端测试
  37. reflection.Register(s)
  38. log.Printf("serving on %s\n", addr)
  39. if err := s.Serve(lis); err != nil {
  40. log.Fatalf("failed to serve: %v", err)
  41. }
  42. }
  43. func SignalHandler(httpServer *http.Server) {
  44. var (
  45. c chan os.Signal
  46. s os.Signal
  47. )
  48. c = make(chan os.Signal, 1)
  49. signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
  50. for {
  51. s = <-c
  52. switch s {
  53. case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
  54. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  55. println("Shutdown http server")
  56. if err := httpServer.Shutdown(ctx); err != nil {
  57. println("http server failed to shutdown", err.Error())
  58. }
  59. cancel()
  60. println("Server exited")
  61. return
  62. default:
  63. return
  64. }
  65. }
  66. }