Skip to content

Instantly share code, notes, and snippets.

@gerep
Created March 11, 2019 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerep/bb9c38f37c241f021bc75c130f3e94c9 to your computer and use it in GitHub Desktop.
Save gerep/bb9c38f37c241f021bc75c130f3e94c9 to your computer and use it in GitHub Desktop.
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