FAQ
Hi!
I have find three ways of context-aware HTTP request cancelation, and have
question what is better to use?
Problem: given ctx * context.Context
<https://godoc.org/golang.org/x/net/context> and some request that should
be canceled on ctx.Done. How to handle it?
Solutions:
1) oldstyle, from first blog.golang post about context.
Use Deprecated http.Transport.CancelRequest and additional goroutine

func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error { // Run the HTTP request in a goroutine and pass the response to f. tr := &http.Transport{} client := &http.Client{Transport: tr} c := make(chan error, 1) go func() { c <- f(client.Do(req)) }() select { case <-ctx.Done(): tr.CancelRequest(req) <-c // Wait for f to return. return ctx.Err() case err := <-c: return err }}

2) new style - pass Done channes, from first blog.golang post about context. http.Client transport should support this

func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error { tr := &http.Transport{} client := &http.Client{Transport: tr}

     req.Cancel = ctx.Done return f(client.Do(req)) }


3) use ctxhttp <https://godoc.org/golang.org/x/net/context> helper function. Very simple, client transport should't support new-style req.Cancel cancelation. But starts two or three goroutines inside! Seems to me, it is big overhead.

func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {

     tr := &http.Transport{} client := &http.Client{Transport: tr}

     return f(ctxhttp.Do(req)) }


P.S. creating new http.Transport and http.Client for every request is bad style - don't do this.








--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

  • Vladimirskipor at Apr 18, 2016 at 7:57 am
    Also I have found that ctxhtt.Do returns ctx.Err() if request was canceled
    by ctx.Done, and this is helpful to distinguish cancelation errors and
    something unexpected

    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedApr 17, '16 at 2:29p
activeApr 18, '16 at 7:57a
posts2
users1
websitegolang.org

1 user in discussion

Vladimirskipor: 2 posts

People

Translate

site design / logo © 2021 Grokbase