Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make BasicFunc support dependency injection #18

Open
vpereira opened this issue Feb 18, 2015 · 3 comments
Open

Make BasicFunc support dependency injection #18

vpereira opened this issue Feb 18, 2015 · 3 comments

Comments

@vpereira
Copy link

I was able to solve this problem, using db as global variable. However, would be better if I could pass it to my callback (that today, accepts just two params - user and password). Could you support a variable number of params, where I could for example pass the db handle? I stumbled many times in this question and either I found a "use another middlewear" or "set your db variable global"..

@attilaolah attilaolah changed the title pattern to integrate db interaction in the auth.BasicFunc callback Make BasicFunc support dependency injection Feb 19, 2015
@attilaolah
Copy link
Contributor

This is a little tricky because (I think) we would have to inject the username and password in the context as well in order for BasicFunc to be able to access it.

@vpereira
Copy link
Author

maybe if the function accepts not 2 strings, but a struct, where at least includes the fields username and password?

@attilaolah
Copy link
Contributor

No you can't do that with a struct.

You can, however, do that with an interface, but that seems like too much complexity. After all, you could just pass in the db in a closure. Or pass in a method to auth.BasicFunc, and have the method access the db via the struct.

func main() {
    // …
    m.Use(auth.BasicFunc(&(DBAuth{…}).Authenticate))
}

type DBAuth struct {
    // …
}

func (a *DBAuth) Authenticate(username, password string) bool {
    db := a.Database()
    // authenticate username and password using the db…
}

func (a *DBAuth) Database() *DB {
    return &DB{…}
}

…you get the idea.


Summary: what you want can already be achieved without DI. I don't see a great need for DI here, but, if someone wants to implement this, why not. Just send a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants