gin icon indicating copy to clipboard operation
gin copied to clipboard

javascript fetch AbortController and cancellation

Open MarcMagnin opened this issue 4 years ago • 4 comments

Description

Cancelling a request with the AbortController doesn't seems to cancel the request context. Details about the AbortController: https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort

How to reproduce

Query an endpoint via javascript while aborting the request like the example on the mozilla doc.

Expectations

Gin c.Request.Context().Done() triggers.

Actual result

Gin c.Request.Context().Done() never gets triggered.

Environment

  • go version: 1.14.1
  • gin version (or commit ref): 1.6.3
  • operating system: Ubuntu 18

MarcMagnin avatar May 25 '20 10:05 MarcMagnin

Can you share any specific implementation of that interface you're using? If I assume that to be (npm abort-controller), then it looks like the connection is not getting closed from client. And hence, gin has no idea about the abort event.

arajhansa avatar Jun 10 '20 05:06 arajhansa

Thanks for the reply! Sure, we basically use the browser AbortController API (not from the npm package) like the following:

[javascript]
var controller = new AbortController();
var signal = controller.signal;
fetch(url, {signal});

When calling controller.abort();, I can see that the resquest gets cancelled from the browser dev tools.

The golang context I'm referring to is one accessible within a gin.HandlerFunc:

[golang]
func MySweetHandler(c *gin.Context) {
     ctx := c.Request.Context()
     ...
}

I can't remember for sure but back in time I was using gorilla/mux and I think the cancellation was passed down ok to the golang context.

MarcMagnin avatar Jun 10 '20 08:06 MarcMagnin

I am experiencing the very same issue.

Looks like using c.Request.Context().Done() rather than c.Done() works.

ItalyPaleAle avatar Jul 02 '22 01:07 ItalyPaleAle

Using c.Request.Context().Done() works when I'm cancelling the requests through Insomnia or other basic HTTP client. But when I use specifically the AbortController signal, it's cancelled on the browser but it's not handled or not propagated somehow. Any hint about solving this issue? That might be on the way AbortController works, but I don't find any workaround sadly.

matcornic avatar Dec 21 '22 15:12 matcornic