utrack / clay

Proto-first minimal server platform for gRPС+REST+Swagger APIs
MIT License
289 stars 39 forks source link

As previous PR with some changes #64

Closed karantin2020 closed 5 years ago

karantin2020 commented 5 years ago

fix: Fixed typo in transport/server/opts.go refactor: Deleted CloseNotifier middleware feat: Add pointers to http.Server and grpc.Server

karantin2020 commented 5 years ago

As example:

func main() {
    // Wire up our bundled Swagger UI
    hmux := chi.NewRouter()
    httpSrv := &http.Server{
        ReadTimeout:       15 * time.Second,
        ReadHeaderTimeout: 1 * time.Second,
        IdleTimeout:       60 * time.Second,
        WriteTimeout:      15 * time.Second,
        MaxHeaderBytes:    1 << 20,
    }
    mws := mwgrpc.UnaryPanicHandler(log.Default)
    mw := grpc_middleware.ChainUnaryServer(mws)
    grpcSrv := grpc.NewServer(grpc.UnaryInterceptor(mw))

    impl := &SumImpl{}
    srv := server.NewServer(
        40345,
        server.WithHost("127.0.0.1"),
        server.WithHTTPPort(8312),
        server.WithHTTPMux(hmux),
        server.WithHTTPServer(httpSrv),
        server.WithGRPCServer(grpcSrv),
    )

    var g errgroup.Group

    g.Go(func() error {
        err := srv.Run(impl)
        if err != nil && err != http.ErrServerClosed {
            logrus.Fatal(err)
        }
        return err
    })

    g.Go(func() error {
        // Wait for interrupt signal to gracefully shutdown the server with
        // a timeout of 5 seconds.
        quit := make(chan os.Signal, 1)
        // kill (no param) default send syscanll.SIGTERM
        // kill -2 is syscall.SIGINT
        // kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
        signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
        <-quit
        fmt.Print("\r")
        logrus.Info("Shutdown Server ...")
        var gg errgroup.Group

        gg.Go(func() error {
            ctx, cancel := context.WithTimeout(context.Background(), time.Second)
            defer cancel()
            err := httpSrv.Shutdown(ctx)
            if err != nil {
                logrus.Error("Server Shutdown:", err)
            }
            // catching ctx.Done(). timeout of 5 seconds.
            <-ctx.Done()
            logrus.Info("timeout of 1 second")

            logrus.Info("HTTP Server exiting")
            return err
        })
        gg.Go(func() error {
            grpcSrv.GracefulStop()
            logrus.Info("GRPC Server exiting")
            return nil
        })
        return gg.Wait()
    })
    logrus.Error(g.Wait())
}

With logs:

INFO[0001] Shutdown Server ...                          
INFO[0001] GRPC Server exiting                          
INFO[0002] timeout of 1 second                          
INFO[0002] HTTP Server exiting                          
ERRO[0002] http: Server closed