Tutorial Notebook: A simple CRUD app with Go

Tutorials Notebook is a blog series where I write-up my thoughts & lessons learned after completing a tutorial. A large credit should go to the authors who created the tutorials in the first place.

Tutorial: https://codewithmukesh.com/blog/implementing-crud-in-golang-rest-api/ by Mukesh Murugan


Lately, a couple of things have been motivating me to learn and get better with GoLang.

  1. There's a project that I've wanted to build for a friend since last year;

  2. I'm ending up working more and more in our codebase at work which is all written in Go.

So I figured I'd start from scratch and work towards the goal of building that app for my friend.

Breaking down that task - one thing I'll need to do is create an API that can handle incoming requests. Today, I completed a tutorial to create a very basic app that would enable a user to Create, Retrieve, Update and Delete (CRUD) a product from a database.

Things I Learned

  1. MySQL. It'd been a while since I'd created a database. Helpful commands on mac:

    • brew install mysql - Install the MySQL server on mac.

    • brew services start mysql - Start the MySQL server

    • mysql -u root - Login with username root and no password (default)

    • create database <name>;

    • use database <name>;

    • show tables;

  2. VS Code Shortcut: Typing in hand (+ enter) in VS Code will automatically create a HTTP response handler for you.

  3. Go Pointers

  • You can define what an object is like. In this example, a product consists of 4 pieces of information.
type Product struct {
    ID          uint    `json:"id"`
    Name        string  `json:"name"`
    Price       float64 `json:"price"`
    Description string  `json:"description"`
}
  • A pointer to that struct is used in this HTTP API handler for POST ing (creating) products.
func CreateProduct(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    var product entities.Product
    json.NewDecoder(r.Body).Decode(&product)
    database.Instance.Create(&product)
    json.NewEncoder(w).Encode(product)
}

Where the important lines are:

var product entities.Product - this line creates an "empty" product that contains the 0 (or nil) values defined int he struct.

json.NewDecoder(r.Body).Decode(&product) - In this line, we use the memory address of variable product as denoted by the & to "fill" it with relevant data.

  1. You can even make cURL commands right from VS Code using the REST Client extension.