|
| 1 | +# GoFr Context |
| 2 | +GoFr context is an object injected by the GoFr handler. It contains all the request-specific data, so for each |
| 3 | +request-response cycle a new context is created. The request can be of any type be it an HTTP request, GRPC call or |
| 4 | +a message from Pub-Sub. |
| 5 | +GoFr Context also embeds the **_container_** which maintains all the dependencies like databases, logger, http service clients, |
| 6 | +, metrics manager, etc. This reduces the complexity of the application as users don't have to maintain and keep track of |
| 7 | +all the dependencies by themselves. |
| 8 | + |
| 9 | +GoFr context is an extension of the default go context, providing a wrapper around the request and response providing the |
| 10 | +user access to the dependencies on the go. |
| 11 | + |
| 12 | +# Usage |
| 13 | +## Reading HTTP requests |
| 14 | +`ctx.Request` can be used to access the underlying request which provides the following methods to access different |
| 15 | +parts of the request. |
| 16 | +- `Context()` - to access the context associated with the incoming request |
| 17 | + ```go |
| 18 | + ctx.Request.Context() |
| 19 | + ``` |
| 20 | +- `Param(string)` - to access the query parameters present in the request, it returns the value of the key provided |
| 21 | + ```go |
| 22 | + // Example: Request is /configs?key1=value1&key2=value2 |
| 23 | + value := ctx.Request.Param("key1") |
| 24 | + // value = "value1" |
| 25 | + ``` |
| 26 | +- `PathParam(string)` - to retrieve the path parameters |
| 27 | + ```go |
| 28 | + // Consider the path to be /employee/{id} |
| 29 | + id := ctx.Request.PathParam("id") |
| 30 | + ``` |
| 31 | +- `Bind(interface{})` - to access a decoded format of the request body, the body is mapped to the interface provided |
| 32 | + ```go |
| 33 | + // incoming request body is |
| 34 | + // { |
| 35 | + // "name" : "trident", |
| 36 | + // "category" : "snacks" |
| 37 | + // } |
| 38 | + |
| 39 | + type product struct{ |
| 40 | + Name string `json:"name"` |
| 41 | + Category string `json:"category"` |
| 42 | + } |
| 43 | +
|
| 44 | + var p product |
| 45 | + ctx.Bind(&p) |
| 46 | + // the Bind() method will map the incoming request to variable p |
| 47 | + ``` |
| 48 | +- `HostName()` - to access the host name for the incoming request |
| 49 | + ```go |
| 50 | + // for example if request is made from xyz.com |
| 51 | + host := ctx.Request.HostName() |
| 52 | + // the host would be http://xyz.com |
| 53 | + // Note: the protocol if not provided in the headers will be set to http by default |
| 54 | + ``` |
| 55 | + |
| 56 | +## Accessing dependencies |
| 57 | +As mentioned earlier, GoFr context embeds the container object which provides the access to |
| 58 | +all the injected dependencies by the users. Users can access the fields and methods provided |
| 59 | +by the **_container_**. |
0 commit comments