In the beginning of my controller I create a context with a timeout like this:
ctx, cancel := context.WithTimeout(context.Background(), time.Second * 10)
defer cancel()
And then I use this context in each database request like this:
QueryRowContext(ctx, query, ...args) // where ctx is context
However, when I load my test program, I notice that some of my requests return error "pq: canceling statement due to user request"
. And the more requests I make, the more errors I get.
But, if I don't use context with timeout, but rather use just context.Background()
, I get no errors regardless of the amount of requests.
Each request takes about 50ms, so timeout cannot occur. I tried context with cancel context.WithCancel(context.Background())
and I also get these errors.
What may be a reason that these errors occur?
// create context to cancel working if 10 seconds passed
ctx, cancel := context.WithTimeout(context.Background(), time.Second * 10)
defer cancel()
// parses queries
var response []byte
request := model.GetProductByBarcodeRequest{}
barcode := r.URL.Query().Get("barcode")
storeID := r.URL.Query().Get("store_id")
transactionType := r.URL.Query().Get("type")
request.Barcode = &barcode
request.StoreID = &storeID
request.Type = &transactionType
// processing
result, err := model.GetProductByBarcode(ctx, request)
response = controller.ToJson(result, err)
// writing response to user
w.Write(response)