Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

go - Graceful stop of gin server

I'm trying to implement a clean way of gracefully stopping my gin server using a parent context passed to my class. Here the current code I have

Is there a cleaner way to do this? It feels like a lot of boilerplate code and unnessesary e.g. using an infinite loop for such an easy task.

func (instance *MyListener) Listen(ctx context.Context) error {
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()
    
    engine := gin.Default()
    engine.POST("/doStuff", func(c *gin.Context) {          
        instance.doStuff()
        c.Status(200)
    })

    instance.httpSrv = &http.Server {
        Addr:    ":8080",
        Handler: engine,
    }

    // Initializing the server in a goroutine so that
    // it won't block the graceful shutdown handling below
    go func() {
        if err := instance.httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            logging.Log.Error("Could not start listener", zap.Error(err))
        }
    }()

    loop:
    for {
        select {
            case <- ctx.Done():
                break loop
            default:
                time.Sleep(1000)
        }
    }

    ctx, cancel = context.WithTimeout(ctx, 2 * time.Second)
    if err := instance.httpSrv.Shutdown(ctx); err != nil {
        logging.Log.Error("Server forced to shutdown:", err)
    }

    return nil
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This:

loop:
for {
    select {
        case <- ctx.Done():
            break loop
        default:
            time.Sleep(1000)
    }
}

Could be replaced with this:

<- ctx.Done()

And it would be just as effective and more efficient. Other than that, the solution you have seems clean, clear, and correct.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...