Skip to content

Commit d1599ea

Browse files
network: allow breaking async job loop when Ctrl+C is pressed
This break the async job loop when Ctrl+C is pressed during async job polling. May address #126 Signed-off-by: Rohit Yadav <[email protected]>
1 parent 6323a31 commit d1599ea

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

cmd/network.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import (
3030
"net/http/cookiejar"
3131
"net/url"
3232
"os"
33+
"os/signal"
3334
"sort"
3435
"strings"
3536
"time"
@@ -148,7 +149,18 @@ func pollAsyncJob(r *Request, jobID string) (map[string]interface{}, error) {
148149
spinner := r.Config.StartSpinner("polling for async API result")
149150
defer r.Config.StopSpinner(spinner)
150151

152+
interrupted := false
153+
c := make(chan os.Signal, 1)
154+
signal.Notify(c, os.Interrupt)
155+
go func() {
156+
<-c
157+
interrupted = true
158+
}()
159+
151160
for {
161+
if interrupted {
162+
return nil, errors.New("API job query interrupted")
163+
}
152164
select {
153165
case <-timeout.C:
154166
return nil, errors.New("async API job query timed out")
@@ -234,8 +246,8 @@ func NewAPIRequest(r *Request, api string, args []string, isAsync bool) (map[str
234246
config.Debug("NewAPIRequest API request URL:", requestURL)
235247

236248
var response *http.Response
237-
response,err = executeRequest(r, requestURL, params)
238-
if (err != nil) {
249+
response, err = executeRequest(r, requestURL, params)
250+
if err != nil {
239251
return nil, err
240252
}
241253
config.Debug("NewAPIRequest response status code:", response.StatusCode)
@@ -251,8 +263,8 @@ func NewAPIRequest(r *Request, api string, args []string, isAsync bool) (map[str
251263
requestURL = fmt.Sprintf("%s?%s", r.Config.ActiveProfile.URL, encodeRequestParams(params))
252264
config.Debug("NewAPIRequest API request URL:", requestURL)
253265

254-
response,err = executeRequest(r, requestURL, params)
255-
if (err != nil) {
266+
response, err = executeRequest(r, requestURL, params)
267+
if err != nil {
256268
return nil, err
257269
}
258270
}
@@ -281,7 +293,7 @@ func NewAPIRequest(r *Request, api string, args []string, isAsync bool) (map[str
281293
}
282294

283295
// we can implement further conditions to do POST or GET (or other http commands) here
284-
func executeRequest(r *Request, requestURL string, params url.Values) (*http.Response, error){
296+
func executeRequest(r *Request, requestURL string, params url.Values) (*http.Response, error) {
285297
if params.Has("password") || params.Has("userdata") {
286298
requestURL = fmt.Sprintf("%s", r.Config.ActiveProfile.URL)
287299
return r.Client().PostForm(requestURL, params)

0 commit comments

Comments
 (0)