package worker import ( "context" "net/http" ) type ServerTask struct { server *http.Server } func NewServerTask(server *http.Server) *ServerTask { return &ServerTask{ server: server, } } func (self *ServerTask) Start(ctx context.Context) error { done := make(chan error) go func() { done <- self.server.ListenAndServe() }() select { // if ListenAndServe error for something other than context.Canceled //(e.g.: address already in use) it trigger done to return sonner with // the return error case err := <-done: return err // in case of context canceled it will manually trigger the server to // shutdown, and return its error, which is most cases, but not limited, is // context.Canceled. case <-ctx.Done(): return self.server.Shutdown(ctx) } }