I put together a simple console app that queries a Postgres database to retrieve football players: either all records or a single record for a given number.
Here’s a SQL script on GitHub to create a roster table with a few player records.
Here’s the Go code, also on GitHub.
Most people familiar with a C type language will be able to read and understand the Go code. Syncfusion has a free book on Go basics.
A few things to note in the Go code.
Go uses the database/sql package for database access. You’ll also need a driver specific to the database system being used. In the import package, the postgres driver is preceded with an underscore, since we don’t directly reference this package. Go will raise an error if a package is imported without being referenced.
We don’t have to worry about explicitly closing the database connection, it will be closed when the referencing variable goes out of scope.
I wanted a basic app that accessed a database, so I’ve covered the straight-forward scenarios. For a real app that would be deployed, there’s a little more I should do. I need to validate the input before passing to the player lookup, as well as better error handling.
For DB access, I’ve hard coded the host name, user name and password in the app. A real app would probably want these values in a config file (as well as obfuscating the password).
I also want to look at creating a REST API for accessing data.
How to build a REST-API using Golang and PostreSQL