Skip to content

Instantly share code, notes, and snippets.

@drtaka
Created January 31, 2020 04:50
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 drtaka/8a13d04a1ba8435e0e351425545a751c to your computer and use it in GitHub Desktop.
Save drtaka/8a13d04a1ba8435e0e351425545a751c to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
"os"
"io"
"context"
"time"
)
/**
HTTP Request で Context のタイムアウトを利用する。
*/
func main() {
const TimeOutSec = 2
client := &http.Client{}
endpoint := "http://example.com"
//endpoint := "http://example.com:8999"
req, _ := http.NewRequest(http.MethodGet, endpoint, nil)
ctx, cancel := context.WithTimeout(context.Background(), TimeOutSec * time.Second)
defer func() {
fmt.Println("OK timeout")
cancel()
}()
ch := make(chan struct{})
go func() {
defer fmt.Println("Exit go routine func")
req = req.WithContext(ctx)
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Error: %s", err)
ch <- struct{}{}
return
}
io.Copy(os.Stdout, resp.Body)
fmt.Println("Done go routine")
time.Sleep(5 * time.Second)
ch <- struct{}{}
}()
fmt.Println("waiting...")
<-ch
fmt.Println("All done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment