Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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