100 Days of Code, Day 3: It’s Alive!

After 3 days, I finally have working code! My NoSQL database (affectionately known as GoSQL) can receive database commands and properly manipulate data. It may not be pretty but it’s still really rewarding to have a “finished” product in programming language that I had no knowledge of on Monday.

Finishing the project required adding the ability to read and write from and to a JSON file. I’ll show you how to add this into your Go code and one trick that might be blocking you.

Reading from the JSON Database

Snip20180516_3To read our file, we use the ioutil package. We can take the result and use the Unmarshal function. Unmarshal will deserialize the JSON from a byte array into a structure that you define. In this case, it will deserialize into our db variable of type Database

Writing into the JSON Database

Snip20180516_4

Once we’ve manipulated or data, we want to save into our JSON file. We will use the sibling method of Unmarshal, Marshal!

marshall

This time, we are creating a byte array using JSON encoding that we can write to our file.

An important note!

If you are going to serialize a struct to JSON, the struct’s properties have to be exportable. This is notated by capitalizing first letter of a property’s name in the struct definition. Making a property, variable, constant, or struct exportable means that its usable in other files. Think of this like using the “Public” or “Global” keyword in other programming languages.

What’s Next?

I now have a database that can create, update, get, and delete key value pairs and store them in a file for later use. It’s rather rudimentary, but it works! This opens up opportunities for other apps that need to store simple amounts of data. Come back tomorrow to see how we can put this database into action!

One thought on “100 Days of Code, Day 3: It’s Alive!

Leave a comment