This blog post covers the topic connect to a PostgreSQL database, create tables, insert data and use a file from a GitHub project and do the implementation with GO. That blog post is also related to my last blog post called Connect to a PostgreSQL database using GO. You find the related code to my new blog post in that GitHub project.
The file to create the example tables and content is a part of the GitHub project called Multi-tenancy assets for IBM clients to build SaaS.
Connect to a PostgresSQL database, create tables, insert data using a file from a GitHub project.
- Connect to the database
- Get a file from a GitHub project with the SQL statements to create tables and insert data
- Execute the SQL statement
- Verify one value with a query
Each step contains the link to the line in the source code inside the GitHub repository.
- Create HTTP request using the GitHub API
- Define HTTP header
- Create client
- Invoke HTTP request
- Verify the request status
- Get only body from response
- Convert body to JSON content
- Extract and decode file content from JSON
- Connect to a database
- Create a SQL statement from file content
- Verify the created tables with a query
As I said before, we use an example file from a GitHub project called Multi-tenancy assets for IBM clients to build SaaS. So, we need to get a bit familiar with the GitHub public APIs.
- Example url we use:
Mapping to the used GitHub API endpoint:
These are the related values of the example GitHub API endpoint above:
- GitHub API: https://api.github.com/repos/
- Name: “IBM/”
- Repo: “multi-tenancy”
- GitHub API: /contents/
- Filename: “installapp/postgres-config/create-populate-tenant-a.sql”
For more details visit the GitHub public APIs documentation.
- How to convert an HTTP response body to a string in Go
- Go by Example: Base64 Encoding
- How to get a file via GitHub APIs
- Go by Example: JSON
- Access HTTP response as string in Go
- pgx – PostgreSQL Driver and Toolkit
These are the steps you need to follow to run the example on your local machine.
Note: You need a running PostgresSQL database somewhere
git clone https://github.com/thomassuedbroecker/go-access-postgres-example.git cd go-access-postgres-example
Step 2: Verify that the mod file “go.mod”
cd gopostgressql ls
Note: Don’t forget to insert your DATABASE_URL.
go run .
We touched in that simple example different essentials and useful topics in GO programming I would say (for example: base64, access HTTP endpoints, handle JSON and so on) and that makes it worth to take a note 😉
I hope this was useful for you and let’s see what’s next?
#go, #postgressql, #github, #buildlabs4saas