Using Go Context to Pass Information Through Different Layers
Silvio Ubaldino
Fullstack Software Engineer | Backend Developer | Golang | Java | Microservices | SQL | NoSQL | React | Docker | AWS
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:
This approach keeps your code clean and focused, avoiding unnecessary parameter passing while ensuring the required information is available where it's needed.
Nice perspective
Senior .NET Software Engineer | Senior Full Stack Developer | C# | .Net Framework | Azure | React | SQL | Microservices
2 个月Great content, thanks for sharing!
Data Engineer | Azure | Azure Databricks | Azure Data Factory | Azure Data Lake | Azure SQL | Databricks | PySpark | Apache Spark | Python
3 个月Thanks for sharing !
Senior FullStack Developer | C# | Angular | React.js | Azure | RabbitMQ | Node.js | AWS | Sql Server | Oracle | Postgresql | Sqlite | MongoDB | Senior FullStack Engineer
3 个月Interesting
Fullstack Software Engineer | Node | Typescript | React | Next.js | AWS | Tailwind | NestJS | TDD | Docker
3 个月Thanks for sharing