bilibili / kratos-demo

a project that use kratos
187 stars 70 forks source link

cmd下main loop下的defer是否放到闭包里会好一些 #1

Closed freehere107 closed 5 years ago

freehere107 commented 5 years ago
    for {
        s := <-c
        log.Info("get a signal %s", s.String())
        switch s {
        case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
            ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
            defer cancel() //这里
            grpcSrv.Shutdown(ctx)
            httpSrv.Shutdown(ctx)
            log.Info("kratos-demo exit")
            svc.Close()
            time.Sleep(time.Second)
            return
        case syscall.SIGHUP:
        default:
            return
        }

改成

    for {
        s := <-c
        log.Info("get a signal %s", s.String())
        switch s {
        case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
            func(){
                ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
                defer cancel()
                httpSrv.Shutdown(ctx)
                log.Info("kratos-demo exit")
                svc.Close()
                time.Sleep(time.Second)
            }()
            return
        case syscall.SIGHUP:
        default:
            return
        }
    }

这样idea就不会报warning了

felixhao commented 5 years ago

@freehere107 idea报的warning是什么?

freehere107 commented 5 years ago

Possible resource leak, 'defer' is called a for loop.Reports defer statements inside loops

lintanghui commented 5 years ago

cancel直接放到svc.Close()下就行了

felixhao commented 5 years ago

@freehere107 已经修复