Will this be OK?

func ListenAndServe(ctx context.Context, srv *http.Server) error {
ctx,cancel := context.WitchCancel(ctx)

wg := sync.WaitGroup{}
defer wg.Wait()

wg.Add(1)
go func(ctx context.Context) {
defer cancel()
                err := srv.ListenAndServe()
fmt.Println("Server err is", err)
}(ctx)

select {
case <-ctx.Done():
srv.Close()
}

return ctx.Err()
}

When the http server error and quit, it will call the cancel to unblock the 
select.
When the ctx is cancelled, it will call svr.Close() to unblock the server.
Does it works?

On Wednesday, April 5, 2017 at 2:02:16 AM UTC+8, Pierre Durand wrote:
>
> Hello
>
> I wrote a small helper to stop an HTTP Server when a Context is canceled.
> https://play.golang.org/p/Gl8APynVdh
>
> What do you think ?
> Is it OK to use context cancellation for stopping long running functions ?
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to