Metaprogram in Go
How to use Golang to metaprogram a CRUD API.
Most modern sites implement some kind of MV* framework, either formally or loosely. If you code a lot, you are likely writing many models (M) over and over, that are mostly similar in structure and only vary in the details of the schema. You define the SQL schema, you create the structs, and you put together some basic CRUD API between the two. Then you may tweak it over time as you develop the application logic. Wouldn’t it be nice to automate some of that, to reduce both time and bugs?
In this article, we will do just that. We will explore metaprogramming in Go to automatically create simple CRUD API based on SQL table definitions.
Introduction
Metaprogramming is essentially writing a program to write a program. So you are one level removed from the specific program and instead are solving for a more general class of program. A somewhat well-known example of this is Rails generators (as in Ruby on Rails). By just running rails new test
you create a fully functional project called “test”. Metaprogramming typically takes a bit longer, but in the end you have a tool that you can re-use on similar problems.
I usually use Postgres for my DB, so I’d like to automatically convert a set of SQL Create Table definitions into Go code API…