Skip to content

Instantly share code, notes, and snippets.

@anxiousmodernman
Last active November 22, 2016 23:44
Show Gist options
  • Save anxiousmodernman/e7e346bc00dd91f507c3365e895d646e to your computer and use it in GitHub Desktop.
Save anxiousmodernman/e7e346bc00dd91f507c3365e895d646e to your computer and use it in GitHub Desktop.
Good one to study
import (
"errors"
"log"
"net/http"
"time"
"flag"
"fmt"
)
var (
towards = flag.String("towards", "", "the host:port of the server to send to")
)
func main() {
flag.Parse()
err := send()
if err != nil {
log.Fatal("whoops")
}
}
// send wants 200 from the upstream service, or times out.
func send() error {
timeout := time.After(5 * time.Second)
ok := make(chan bool)
go func() {
upstream := fmt.Sprintf("http://%s/ping", *towards)
resp, err := http.Get(upstream)
if err != nil || resp.StatusCode != 200 {
ok <- false
return
}
ok <- true
}()
select {
case <-timeout:
return errors.New("timed out")
case v := <-ok:
if !v {
return errors.New("unexpected upstream response")
}
break
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment