Using Go Context to Pass Information Through Different Layers

Using Go Context to Pass Information Through Different Layers

What is Go Context?

Golang provides a native structure called context, which is highly popular in the community due to its specific and essential use cases. The primary purpose of context is to manage the lifecycle of requests, especially in concurrent systems. It enables sharing configurations like timeouts and deadlines across multiple goroutines seamlessly.

Good Practices for Using Context

While context is a powerful tool, it's important to use it wisely. Adding too many parameters to context is generally discouraged. However, certain use cases are widely accepted by the community—for example, passing an user ID. Let’s explore this use case.

Passing Information Through Layers

In this example API, we have a middleware that receives a user token from a request. The token is validated using an external authentication provider, and an user ID is retrieved. This userID is only needed at the repository layer to execute database queries.

It wouldn't make sense to pass userID as a parameter through all layers and functions of the system. A better approach is to inject userID into the context and retrieve it only where it's required.

Here’s how it works:

  • Middleware Example:



  • Retrieving from Context in Repository:


This approach keeps your code clean and focused, avoiding unnecessary parameter passing while ensuring the required information is available where it's needed.

Mauro Marins

Senior .NET Software Engineer | Senior Full Stack Developer | C# | .Net Framework | Azure | React | SQL | Microservices

2 个月

Great content, thanks for sharing!

回复
Jader Lima

Data Engineer | Azure | Azure Databricks | Azure Data Factory | Azure Data Lake | Azure SQL | Databricks | PySpark | Apache Spark | Python

3 个月

Thanks for sharing !

Willian de Castro

Senior FullStack Developer | C# | Angular | React.js | Azure | RabbitMQ | Node.js | AWS | Sql Server | Oracle | Postgresql | Sqlite | MongoDB | Senior FullStack Engineer

3 个月

Interesting

Kaique Perez

Fullstack Software Engineer | Node | Typescript | React | Next.js | AWS | Tailwind | NestJS | TDD | Docker

3 个月

Thanks for sharing

要查看或添加评论,请登录

Silvio Ubaldino的更多文章

社区洞察

其他会员也浏览了