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.
There's a project that I've wanted to build for a friend since last year;
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
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 servermysql -u root
- Login with usernameroot
and no password (default)create database <name>;
use database <name>;
show tables;
VS Code Shortcut: Typing in
hand
(+ enter) in VS Code will automatically create a HTTP response handler for you.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.
- You can even make cURL commands right from VS Code using the REST Client extension.