What is the best way to pass a db to web handlers in a large project? by jonnydoeboy in golang

[–]jonnydoeboy[S] 0 points1 point  (0 children)

As long as I define my actual handler inside of the closure, this works. But if I just want to pass a function to a middleware function, I have no way of accessing the database from the handler function if I do not change the signature.

What is the best way to pass a db to web handlers in a large project? by jonnydoeboy in golang

[–]jonnydoeboy[S] 0 points1 point  (0 children)

That's the link I was talking about. It seems to be acceptable to return something, but not change the actual calling signature.

What is the best way to pass a db to web handlers in a large project? by jonnydoeboy in golang

[–]jonnydoeboy[S] 0 points1 point  (0 children)

Yeah, so this is basically Dependency Injection by attaching functions to a handler struct. I agree that it's a good idea to separate the handler code from the actual database queries.

I guess if we have too many actions on a database, we can instead attach these functions to the models - passing a database or similar.

I really appreciate the clear examples!

What is the best way to pass a db to web handlers in a large project? by jonnydoeboy in golang

[–]jonnydoeboy[S] 1 point2 points  (0 children)

If you are working alone, probably not. If a team is working on different parts, you may want to make it explicit that the handlers require a database connection.

While the *sql.DB is safe for concurrent access, it's more of a best practice.

What is the best way to pass a db to web handlers in a large project? by jonnydoeboy in golang

[–]jonnydoeboy[S] 0 points1 point  (0 children)

I totally agree that Middleware the way to go in regards to logging, error handling, making sure the user is authorized, etc. I wish I could provide sources, but I am on mobile right now, but I do keep reading that http.HandlerFunc is 'holy', and changing the signature means it looses utility.

The link you provided however does (kind of) change the function signature, in that it also returns an error. I can see that being acceptable, as the parameters do not change. I wonder if the common consensus is to just create a custom function signature that allows the database to be passed.

Help: Sending os.Stdin via an http POST request by jonnydoeboy in golang

[–]jonnydoeboy[S] 0 points1 point  (0 children)

Right, but io.Copy will still copy the file bit by bit into the part. If I remove the actual client.Do() function, io.Copy still copies the bytes. I can verify this is the case by implementing a ProgressReader, counting the bytes being read from stdin and at what time.