Created
March 11, 2019 13:32
-
-
Save gerep/bb9c38f37c241f021bc75c130f3e94c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"net/http" | |
"time" | |
) | |
func main() { | |
success := make(chan bool) | |
timeout := 300 * time.Millisecond | |
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)) | |
defer cancel() | |
go consulta(ctx, success) | |
select { | |
case <-ctx.Done(): | |
fmt.Println("cancelado: ", ctx.Err()) | |
case status := <-success: | |
if status { | |
fmt.Println("sucesso na chamada") | |
} else { | |
fmt.Println("erro na chamada") | |
} | |
} | |
} | |
func consulta(ctx context.Context, success chan bool) { | |
defer close(success) | |
req, err := http.NewRequest("GET", "http://www.google.com.br", nil) | |
if err != nil { | |
success <- false | |
return | |
} | |
req = req.WithContext(ctx) | |
client := http.DefaultClient | |
_, err = client.Do(req) | |
if err != nil { | |
fmt.Println("erro client.Do()", err) | |
success <- false | |
return | |
} | |
success <- true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment