0

first I want to specify our architecture. Client -> Grpc Gateway -> Server In our architecture, we use a gateway to process and authenticate requests and then pass it to the Server application. in the Grpc Gateway, we use alice package to chain some middlewares. here I have 2 questions.

  1. what happens to the context of each request that passes to the next middleware? does the second middleware has the passed context from the first middleware in its request Header(I mean req.Header) or in its request Context object? (I mean req.Context())
  2. what happens to the Server application request, when we send some request with Context object in Go (I mean req.WithContext(ctx))? does the context containment go into the request Header? if the answer is no, then what happens to the Context?

In my Server application, I try to log the context of the request but I don't get anything worthy and comparable to what I send from Grpc Gateway. So I'm confused now. I appreciate any kind of notion. Thanks

  • 6
    The context itself doesn't really gets sent. If you use something like `context.WithTimeout(context.Background(), time.Second)`, and the request takes longer than 1s to complete, it'll get cancelled. The connection gets closed, and so the application which received the request can check `<-req.Context().Done()`. If you _"pass down"_ the context of the initial request, everything related to that context can be notified and cancelled if the context has expired (e.g. DB queries, subsequent requests, routines, etc...) – Elias Van Ootegem Jul 28 '23 at 13:57
  • This is especially useful in a GRPC context when you're dealing with streams, those commonly fetch data in a routine, so you just push the data onto a channel, in a select that either tries to write to the channel, but you add a `case <-ctx.Done()`, and close the channel if that happens. – Elias Van Ootegem Jul 28 '23 at 13:58
  • 2
    so you mean that if I want to send something with request I should put it in headers or somewhere else in request? – Amirsadra Abdollahi Jul 28 '23 at 14:41
  • 2
    No, a context is only relevant in the scope of a go process. you can't pass a context reference through an htp request. – erik258 Jul 28 '23 at 18:46
  • 1
    @AmirsadraAbdollahi the request object has the `Header` for headers, and a `PostForm` field for data. `PostForm` is a `url.Values` type, which is defined as `type Values map[string][]string`. These are the fields are where you set the payload. The context is, quite literally, the context in which the request is performed (for example a routine). If all routines sharing a context need to be terminated, the context is cancelled and all routines that are associated with it can be notified and cleanly terminate – Elias Van Ootegem Aug 01 '23 at 08:59

0 Answers0