Skip to content

Instantly share code, notes, and snippets.

@gerep
Created Mar 11, 2019
Embed
What would you like to do?
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