Created
January 31, 2020 04:50
-
-
Save drtaka/8a13d04a1ba8435e0e351425545a751c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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