Injecting dependencies
Now that we can be sure that a request has a valid API key and is CORS-compliant, we must consider how handlers will connect to the database. One option is to have each handler dial its own connection, but this isn't very DRY (Don't Repeat Yourself) and leaves room for potentially erroneous code, such as code that forgets to close a database session once it is finished with it. It also means that if we wanted to change how we connected to the database (perhaps we want to use a domain name instead of a hardcoded IP address), we might have to modify our code in many places, rather than one.
Instead, we will create a new type that encapsulates all the dependencies for our handlers and construct it with a database connection in main.go
.
Create a new type called Server
:
// Server is the API server. type Server struct { db *mgo.Session }
Our handler functions will be methods of this server, which is how they will be able to access the database session.