Introducing Cheers Alerts


Cheer Alerts Demo GIF

This week, a friend decided to create his own JavaScript library. It was a small and simple in-browser notification library called 'Cheers Alert'. The library was inspired by Toastr, and as of this writing, depends on jQuery and FontAwesome.

The library is already available on npm. I have submitted a pull request that added [Grunt] to this project. This enabled the library to be bundled as a standalone browser library through the use of Browserify and other Grunt plugins such as Uglify and mincss. This automation allowed him to easily maintain and develop future versions of the library. Aside from npm, the library can also be installed through Bower.

As this is his first open source package, he will be actively developing this library. It's open for feedback and contributions, so please check the source out at Github.

You can try the library out by visiting the demo page.

Basic OOP and Composition in Go

I have been studying the Go programming language for several weeks now and thought about writing a series of posts to share what I have learned so far. I figured that it will be an excellent way to reinforce my understanding of the language. I initially thought about writing a post that will discuss concurrency in Go but it turned out that I am not yet eloquent enough to talk about basic concurrency patterns with goroutines and channels. I decided to set the draft aside and write about something I am more comfortable with at the moment: basic object-oriented patterns and composition in Go.

One of the best things I like about Go is its terseness. It made me realize that being advanced does not necessarily need to be complex. There are only a few reserved words, and just going through some of the basic data structures will enable you to read and comprehend most Go projects at Github. In fact, Go is not an object oriented language in the purest sense. According to the Golang FAQ:

Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, “unboxed” integers. They are not restricted to structs (classes).

If Go is not an object-oriented language and everyone is going crazy about Functional Programming in the web development world, then why bother learning OOP patterns in Go? Well, OOP is a widely taught paradigm in CS and IT curricula around the world. If used correctly, I still believe that object-oriented patterns still have its place in modern software development.

Using structs

Go does not have a class similar to a real object-oriented language. However, you can mimic a class by using a struct and then attaching functions to it. The types defined inside the struct will act as the member variables, and the functions will serve as the methods:

package main

import "fmt"

type person struct {
  name string
  age  int
}

func (p person) talk() {
  fmt.Printf("Hi, my name is %s and I am %d years old.\n", p.name, p.age)
}

func main() {
  p1 := person{"John Crisostomo", 25}
  p1.talk()
  // prints: "Hi, my name is John Crisostomo and I am 25 years old."
}

On our example above, we have declared a type struct called person with two fields: name and age. In Go, structs are just that, a typed collection of fields that are useful for grouping together related data.

After the struct declaration, we declared a function called talk. The first parenthesis after the keyword func specifies the receiver of the function. By using pof type person as our receiver, every variable of type person will now have a talkmethod attached to it.

We saw that in action on our main function where we declared and assigned p1to be of type person and then invoking the talk method.

Overriding methods and method promotion

struct is a type, hence, it can be embedded inside another struct. If the embedded struct is a receiver of a function, this function gets promoted and can be directly accessed by the outer struct:

package main

import (
	"fmt"
)

type creature struct {}

func (c creature) walk() {
  fmt.Println("The creature is walking.")
}

type human struct {
  creature
}

func main() {
  h := human{
    creature{},
  }
  h.walk()
  // prints: "The creature is walking."
}

We can override this function by attaching a similarly named function to our human struct:

package main

import (
	"fmt"
)

type creature struct {}

func (c creature) walk() {
  fmt.Println("The creature is walking.")
}

type human struct {
  creature
}

func (h human) walk() {
  fmt.Println("The human is walking.")
}

func main() {
  h := human{
    creature{},
  }
  h.walk()
  // prints: "The human is walking."
  h.creature.walk()
  // prints: "The creature is walking."
}

As we can see on our contrived example, the promoted method can easily be overridden, and the overridden function of the embedded struct is still accessible.

Interfaces and Polymorphism

Interfaces in Go are used to define a type's behavior. It is a collection of methods that a particular type can do. Here's the simplest explanation I can muster: if a struct has all of the methods in an interface, then it can be said that the struct is implementing that interface. This is a concept that can be easily grasped through code, so let us make use of our previous example to demonstrate this:

package main

import (
	"fmt"
)

type lifeForm interface {
   walk()
}

type creature struct {}

func (c creature) walk() {
  fmt.Println("The creature is walking.")
}

type human struct {
  creature
}

func (h human) walk() {
  fmt.Println("The human is walking.")
}

func performAction(lf lifeForm) {
  lf.walk()
}

func main() {
  c := creature{}
  h := human{
    creature{},
  }

  performAction(c)
  // prints: "The creature is walking."
  performAction(h)
  // prints: "The human is walking."
}

In this modified example, we declared an interface called lifeForm which has a walk method. Just like what we have discussed above, it can be said that both creature and human implements the interface lifeForm because they both have a walk method attached to them.

We also declared a new function called performAction, which takes a parameter of type lifeForm. Since both c and h implements lifeForm, they can both be passed as an argument to performAction. The correct walk function will invoked accordingly.

Wrap up

There is so much more to object-oriented programming than what we have covered here but I hope it is enough to get you started in implementing class-like behavior with Golang's structs and interfaces. On my next post, I will talk about goroutineschannels and some basic concurrency patterns in Go. If there's something you would like to add up to what I have covered here, please feel free to leave a comment.

Cebu Open Hackathon 2017

There will be an upcoming hackathon next month, brought to you by Snapzio Rapid Software Solutions in collaboration with iiOffice Cebu. Whether you have an awesome app idea or just wanted to spend the weekend prototyping with a new stack, this event is perfect for all developers who want to showcase their software craftsmanship skills. It will also be an awesome opportunity to meet new developers and discuss new trends in the fast-paced world of software development.

The event will take place at iiOffice Cebu (Arlinda V. Paras Bldg., Don Gil Garcia St., Cebu City, Philippines 6000, near the Cebu Provincial Capitol) on March 24 - 25, 2017(07:00pm - 07:00pm). The hackathon will be open to everyone: freelancers, professional developers and even students. Teams can go up to three members, with a registration fee of Php 100.00 for each team member/participant. Deadline of registration will be on March 20, 2017.

Interested participants can register by filling up this form. More information can be found on the Cebu Open Hackathon 2017's Facebook's page.


Enhancing my self-hosted blog with Cloudflare

This post is not sponsored by Cloudflare; it is an update on my self-hosting journey with the Raspberry Pi.

I am happy with the result of the script that I shared on my last post because I no longer have to manually reboot the Pi every time the Internet connection goes down. However, it is still suboptimal; if the Internet connection goes down for an extended period of time, the blog goes down with it. Not only is it bad for would be readers, it was also frustrating on my end. The thought of moving this blog to a cheap cloud instance crossed my mind during the first few days, but I had to think of something more pragmatic. That was when I decided to check Cloudflare out. When I found out that they are offering a free plan that has more features than what I would need for this blog, I was sold.

Cloudflare is a security company that gained notoriety for stopping DDoS attacks through their Content Delivery Network (CDN)-like feature. It can help your site become more performant by caching your static content in their data centers around the world. This enables your site to load faster and allows more concurrency by serving cached content first before hitting your server. Cloudflare offers this and more for free; including three page rules, analytics, free SSL through their network and even enabling security measures like HTTP Strict Transport Security (HSTS). All of these can be easily configured in their nice looking dashboard. If you want to read more about the company's history, here is a good article about their humble beginning.

Getting a Cloudflare account is straightforward. A walkthrough video of the initial setup process is available on their landing page. In a nutshell, the process only has three steps:

  • Signing up with your email address and password
  • Adding your domain
  • Pointing your domain's nameservers to Cloudflare's own nameservers

After going through those steps quickly, you will be presented with a modern, easy to use admin interface:
Cloudflares dashboard image

It will be impossible to discuss all of what Cloudflare has to offer in a single post, so I will just write about the tweaks that I did to suit my current self-hosted Raspberry Pi setup.

Cypto

I obtained my domain's SSL certificate through Let's Encrypt, a trusted certificate authority that issues certificates for free. Since I have my own certificate configured on NGINX, I do not need to use Cloudflare's free SSL. I just selected Full (Strict) mode under SSL and enabled HSTS, Opportunistic Encryption and Automatic HTTPS Rewrites.

Speed

I enabled Auto Minify for both Javascript and CSS to optimize load times and save on bandwidth. I decided against minifying the HTML to preserve the blog's markup, which in my opinion is important for search engine optimization. I also enabled the Accelerated Mobile Links support for a better mobile reading experience. They also have a Beta feature called Rocket Loader™ (improves the load time of pages with JavaScript), this is off by default, but I decided to give it a try.

Caching

This is the feature that I needed the most. I clicked on this menu before I even explored the other settings above. I made sure Always Online™ is on, and made some minor adjustments with the Browser Cache Expiration.

Page Rules

Cloudflare gives you three page rules for free, and you can subscribe should you need more. Here's how I made use of my free page rules:

Cloudflares Page Rule Settings


Dynamic DNS Configuration

My blog's DNS records are now being handled by Cloudflare so I need to make sure that they are updated automatically if my ISP gives me a new IP address.

The easiest way to achieve this is to install ddclient from Raspbian's default repository, along with the Perl dependencies:

sudo apt-get install ddclient libjson-any-perl

Unfortunately, this version of ddclient does not support Cloudflare's Dynamic DNS API. We need to download the current version here, and overwrite the executable that has been installed by the previous command:

$ wget http://downloads.sourceforge.net/project/ddclient/ddclient/ddclient-3.8.3.tar.bz2

$ tar -jxvf ddclient-3.8.3.tar.bz2

$ cp -f ddclient-3.8.3/ddclient /usr/sbin/ddclient

We installed the old version first to benefit from the daemon that comes with it. This daemon keeps ddclient running in the background and spawns it automatically after each reboot.

This new version of ddclient looks for the configuration file in a different directory so we need to create that directory and move our old configuration file:

$ sudo mkdir /etc/ddclient
$ sudo mv /etc/ddclient.conf /etc/ddclient

Here's my ddclient.conf for reference:

# Configuration file for ddclient generated by debconf
#
# /etc/ddclient.conf

protocol=cloudflare
zone=johncrisostomo.com
use=web
server=www.cloudflare.com
login=*Enter your cloudflare email address here*
password=*Enter your API key here*
blog.johncrisostomo.com

We can now restart ddclient and check its status to make sure that everything is working as expected:

$ sudo service ddclient restart
$ sudo service ddclient status -l

The last command should give you the current status of the daemon along with the latest event logs. Check the event logs for any error messages or warnings, and if everything turned out to be okay, you should see something similar to this: 

SUCCESS: blog.johncrisostomo.com -- Updated Successfully to xxx.xxx.xxx.xxx.



So far this setup works well and I am happy with the blog's performance. It is a shame that I have not gathered data before Cloudflare to objectively compare the performance boost I am getting out of it. However, the blog's initial loading time has become noticeably faster, at least on my end. I guess we will have to see in the next couple of days.

Troubleshooting my Raspberry Pi's Wireless Issue

It has been almost a week since I decided to self-host my Ghost blog. It was a fun experience and most importantly, I knew a lot of new things that I would not otherwise know. On the less technical side, it inspired me to write more about my learning journey because not only does it solidify what I already know, it also drives me to learn more.

There is a little problem though. My Internet connection is flaky and it causes my blog to be sporadically down throughout the day. This is not intended to be a for-profit blog, however, seeing people share some of my posts while my blog is down was frustrating. I just had to do something about it. I observed the Pi's behavior by writing several BASH scripts and cron jobs that makes sure these events are logged. Sifting through the logs after work, I found out that aside from the ISP problem, there is another queer phenomenon that was happening. Whenever my home router loses Internet connection, the Raspberry Pi will lose its default gateway; it persists even after rebooting the router.

My initial attempts to fix this issue was to mess with the resolve.conf and /etc/network/interfaces configuration files. I tried everything from manualdhcpand even static. Nothing really fixed the issue and it was still losing the default gateway route whenever the Internet connection goes down. I finally solved this problem by writing a small BASH script:

#!/bin/bash

ping -c1 google.com > /dev/null

if [ $? != 0 ]
then
  echo `date` "No network connection, restarting wlan0" >> /home/uplogs.txt
  /sbin/ifdown 'wlan0'
  sleep 5
  /sbin/ifup --force 'wlan0'
else
  echo `date` "Internet seems to be up" >> /home/uplogs.txt
fi 

The script pings google.com and then checks the exit code. If the ping exited with an error, the Pi restarts the wireless LAN interface. It also logs all these events so that I can check how reliable my Internet connection was throughout the day. It was a quick and dirty fix. Nothing fancy, but it works.