Go 1.7 ããæ¬ä½ã«å ¥ã£ã context ããã±ã¼ã¸ã¯ä¾¿å©ãã¨ããããä»ãå¿ é ã®éå ·ã§ãã以ä¸ã®ããã«æ¸ããã¨ã§ãä¸å®æéã§å¦çããã£ã³ã»ã«ã§ããããã¾ãã
func slowOperationWithTimeout(ctx context.Context) (Result, error) { ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) defer cancel() // releases resources if slowOperation completes before timeout elapses return slowOperation(ctx) }
defer cancel()
ã¨ããã¾ããããã®ããã«ããªãã¨ãªã½ã¼ã¹ãªã¼ã¯ããã®ã§ context 使ãã¨ãã¯ããæ¸ãã®ããã¿ã¼ã³ã§ãã
ãã¦ã以ä¸ã®ããã°ã©ã ã§ãããè¿ã£ã¦ãããã¼ã¿ãå°ãããã¡ã¯åé¡ãªãåãã¾ããã大ããªãã¼ã¿ã«ãªã㨠resp.Body
ã®èªã¿è¾¼ã¿ã§å¿
ãã¨ã©ã¼ãè¿ãããã«ãªãã¾ãã
func doRequest(ctx context.Context, ...) *http.Response { ctx, cancel := context.WithTimeout(ctx, 5 * time.Second) defer cancel() req := http.NewRequest("GET", "http://...", nil) req = req.WithContext(ctx) resp, err := httpClient.Do(req) if err != nil { panic(err) } return resp } func main() { resp := doRequest(context.Background()) defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Println(string(data)) }
doRequest
ãã帰ãæç¹ã§ cancel ããã¦ãã¾ã£ã¦ããããããã®å¾ã® resp.Body ããã®èªã¿è¾¼ã¿ã失æããããã§ãããããã¼ã¿ãå°ãããã¡ã¯ç¹ã«ã¨ã©ã¼ã«ãªããã«æåãã¦ãã¾ããããæ°ã¥ãã«ããç½ ã§ãã
ãã¼ã¿ãå°ãããã¡ã¯æåãã¦ãã¾ãçç±ã¯ãhttp ã¯ã©ã¤ã¢ã³ãå é¨ã§ãã¬ã¹ãã³ã¹ã®ãããã解æããæç¹ã§ body ã®ãã¼ã¿ãèªã¿è¾¼ãã§å é¨çã«ãããã¡ãã¦ããããã§ããbody ãå°ãããã¡ã¯ããã解æå¦çæç¹ã§ãã¹ã¦èªã¾ãã¦ãããããcancel ããã¦ãåé¡ãªãã¨ã