docsy icon indicating copy to clipboard operation
docsy copied to clipboard

Using DB connection in rout

Open nikableh opened this issue 2 years ago • 1 comments

Sorry if it's a wrong place to post this question, but I was not able to find a sufficient answer on the web or in the examples tab on the website.

I have a variable db that represents s database connection. I also have a /register rout represented by registerHandler() that need to save a new user to the database. How do I pass the db into the registerHandler()?

I've found 2 solutions to this problem:

  1. Have the registerHandler() as a method of some MyGlobalAPIContext struct that has all the fields that API routes may need. The issue is that this would result in a so-called "god object" (and it just feels wrong).
  2. Use middleware that would set context.Keys["database] = db (link to docs) before every call to /register rout. This seems fine, but I am very concerned about the performance of creating and populating this Keys object every time you access this rout. What if you have many calls to it? I feel like this might have its toll on performance.

Doing something things like that seems like a very common thing you'd need to do. What is the most common approach?

nikableh avatar Jan 28 '24 22:01 nikableh

Wrong repo, sorry (⁠´⁠-⁠﹏⁠-⁠`⁠;⁠)

nikableh avatar Jan 29 '24 08:01 nikableh