Thursday 8 April 2021

Re-Starting with Go

 I am once again looking at Go, after a break of over eight years. I did not get that far back then, and as I recall the stumbling block was that you can only pass one object (struct in Go) to a template.

My Ruby on Rails project has got every bigger, as indeed has Ruby on Rails itself, with my WAR files now weighing in at 65 Mb, which seems huge to me, and I am getting complaints about speed. So I am at least looking at migrating bits to Go.

I did look at Rust but getting Rust to connect to a PostgreSQL database proved very temperamental. With that in mind, my first concern was getting Go to connect.

Two useful tutorials:

https://www.calhoun.io/connecting-to-a-postgresql-database-with-gos-database-sql-package/

https://www.alexedwards.net/blog/organising-database-access

It seems to be as simple as adding the driver to your go.mod file (which unlike other Rust, Node.js and Rails is done through the command line, rather than editing the file yourself):

go get -u github.com/lib/pq

In your file, import it (the underscore is because the import is really just registering the driver, you do not actually need to access it):

import (
  "database/sql"
  _ "github.com/lib/pq"
)

Then open the connection:

db, err := sql.Open("postgres", "host=localhost port=5432 user=user dbname=godatabase sslmode=disable password=password")

Interacting with the database is much more low level than Rails.