8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GoのHTTP Clientでリクエストを途中でキャンセルする

Last updated at Posted at 2016-11-02

Go 1.7からhttp.TransportのCancelRequestがDeprecatedになってcontextという仕組みを使うのが良いとされるようになった。

キャンセルなし

package main

import (
	//"context"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := http.DefaultClient

	//ctx, cancelFunc := context.WithCancel(context.Background())

	req, err := http.NewRequest("GET", "https://google.com/", nil)
	if err != nil {
		panic(err)
	}

	//req = req.WithContext(ctx)

	ch := make(chan struct{})

	go func() {
		resp, err := client.Do(req)
		if err != nil { // リクエストが成功すればここは通らない
			fmt.Println(err)
			ch <- struct{}{}
			return
		}
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			panic(err)
		}

		fmt.Println(string(body))

		ch <- struct{}{}
	}()

	//cancelFunc()
	<-ch
}

キャンセルあり

package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	client := http.DefaultClient

	ctx, cancelFunc := context.WithCancel(context.Background())

	req, err := http.NewRequest("GET", "https://google.com/", nil)
	if err != nil {
		panic(err)
	}

	req = req.WithContext(ctx)

	ch := make(chan struct{})

	go func() {
		resp, err := client.Do(req)
		if err != nil { // キャンセルされた場合はエラーが返る
			fmt.Println(err) // Get https://google.com/: net/http: request canceled while waiting for connection
			ch <- struct{}{}
			return
		}
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			panic(err)
		}

		fmt.Println(string(body))

		ch <- struct{}{}
	}()

	cancelFunc()
	<-ch
}
8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?