GAE/Go の urlfetch のタイムアウトを設定する

ググると、旧 appgneine パッケージに対する設定方法しか引っかからないので、
google.golang.org/appengine に対する設定方法をメモとして残しておく。

結論から言うと、
context.WithTimeout() or context.WithDeadline() を利用して設定する。

以下は context.WithTimeout() の例。

c, _ := context.WithTimeout(ctx, 30*time.Second)
fetch := urlfetch.Client(c)

*今回は WithTimeout() の2つ目の戻り値の CancelFunc は使わないので、 _ にしています。


ちなみに、旧 appgneine パッケージは以下のように指定する。

client := &http.Client{
  Transport: &urlfetch.Transport{
    Context:  ctx,
    Deadline: 30 * time.Second,
  },
}


google.golang.org/appengine の設定方法はググってもなかなか見つからなかったが、
実は google.golang.org/appengine の readme に context を利用するように記載があったり、

urlfetch.Transport no longer has a Deadline field; set a deadline on the context.Context instead.

https://github.com/golang/appengine#2-update-code-using-deprecated-removed-or-modified-apis


GCPのドキュメントでも言及されていたりする。

Any deadline of the provided context will be used for requests through this client; if the client does not have a deadline then a 5 second default is used.

https://cloud.google.com/appengine/docs/standard/go/urlfetch/reference#Client