Part 1

Recently we had the need for a notification system that will notify us when certain services are down. I decided to write the system using golang This will be my first article and my first time writing in the go language This article consists of the following parts * part one design the system * part two implementing the design * part 3 deploying and testing

design

i decide to use the the observer pattern as the core service for the notification. The diagram below illustrate the observer pattern, for more details about this design pattern please refer to the following link

Enough talking lets go coding, plunder intended Make a file called observer.go We start by making a an observer interface with Notify methods, which will be implemented by the observer ::for now the notification will be a simple message of type string later on will change this once we implemented more advance feature::

`type Observer interface {
        Notify(messsage)
    }`

Next we need a publisher struct, the struct will hold a list (array or observers)

`type Publisher struct {
        ObserversList []Observer
    }`

Will need to add three methods to the publishers, these methods are AddObserver This methods will receive an observer and will add it to the list of observers of the publisher struct

func (p *Publisher) AddObserver(o Observer) {
        p.ObserversList = append(p.ObserversList, o)
    }

RemoveObserver This method will receive an observer and will remove it from the list of observes of the publisher struct

func (p *Publisher) removeObserver(o *Observer) {
        var indexTORemove int
    
        for i, observer := range p.ObserversList {
            if observer == *o {
                indexTORemove = i
                break
            }
        }
        p.ObserversList = append(p.ObserversList[:indexTORemove], p.ObserversList[indexTORemove+1])
    
    }

And the third method is NotifyObservers, this methods will recite a message or anything the publisher wished to notify the observer about

func (p *Publisher) NotifyObservers(message) {
        for _, observer := range p.ObserversList {
            observer.Notify(m)
        }
    }

The code is self explanatory , we loop though the ObserversList and call the Notify function

Now lets see how this code runs ,

Make another file called main.go, in the main function will make a varable of type publisher struct

publisher := Publisher{}

Now we have the publisher and is ready to receive observer, lets make a Person struct to act as a place holder for our observer, we make simple struct that contact name and email address

type Person struct {
        name string
        email string
    } 

Now lets make a person object from the this struct

Person