avatarSylvia Emokpae

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5070

Abstract

do that:</p><div id="2e8b"><pre>eventHandler<span class="hljs-selector-class">.Handle</span>(event1, <span class="hljs-built_in">ExampleMiddlewareFoo</span>(<span class="hljs-built_in">ExampleMiddlewareBar</span>(handle)))</pre></div><h1 id="a8a5">Managing Events with Handlers and Middleware</h1><p id="f869">Most articles I read explain how to use this design pattern; this one deals with implementing the internal logic. So let's start coding.</p><p id="35c4">The full code for this article can be found <a href="https://github.com/xNok/slack-go-demo-socketmode/blob/main/examples/middleware/main.go">here</a> to help you follow along.</p><h2 id="0f88">Designing events</h2><p id="b622">First, we are going to enumerate the list of events that our system can handle. The way we create enumeration in Go is a bit different than in other programming languages. In Go, we are going to use a set of constants sharing the same <code>type</code>. Here I define a type <code>EventType</code>that represents a string with the event's name.</p><div id="b181"><pre>// <span class="hljs-keyword">type</span> <span class="hljs-type">used </span>to enumerate events <span class="hljs-keyword">type</span> <span class="hljs-type">EventType </span>string</pre></div><div id="4817"><pre>const ( event1 EventType <span class="hljs-operator">=</span> <span class="hljs-string">"event1"</span> event2 EventType <span class="hljs-operator">=</span> <span class="hljs-string">"event2"</span> )</pre></div><p id="e041">Next, we define the event itself. In our example, the<code>Event</code> as a type which can be selected among the list of <code>EventType</code> created above.</p><div id="2bc9"><pre><span class="hljs-keyword">type</span> <span class="hljs-type">Event</span> struct { <span class="hljs-type">Type</span> <span class="hljs-type">EventType</span> <span class="hljs-type">Data</span> interface{} }</pre></div><h2 id="df6c">Create an event sender (for test purpose)</h2><p id="60aa">To test our system, we will need to create a small function to send events every 2s. Each<code>Event</code> is transmitted via a <a href="https://tour.golang.org/concurrency/2">channel</a> and, the <code>eventSender</code> below sends a random <code>Event</code> of type <code>event1</code> or <code>event2</code> to a channel.</p><blockquote id="53f3"><p><i>Channels are a type which you can send and receive values, they are great for communication among goroutines. In other words, there are perfect for sending and receive event through your application.</i></p></blockquote><div id="ffd1"><pre><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">eventSender</span><span class="hljs-params">(c <span class="hljs-keyword">chan</span> EventType)</span></span> {</pre></div><div id="7f57"><pre> for { // Send <span class="hljs-selector-tag">a</span> random event <span class="hljs-selector-tag">to</span> the channel rand<span class="hljs-selector-class">.Seed</span>(<span class="hljs-selector-tag">time</span><span class="hljs-selector-class">.Now</span>()<span class="hljs-selector-class">.Unix</span>()) events := []EventType{ event1, event2, } n := rand.<span class="hljs-built_in">Int</span>() % <span class="hljs-built_in">len</span>(events)</pre></div><div id="6101"><pre> c <- events[n] <span class="hljs-comment">// send event to channel</span></pre></div><div id="5285"><pre> // <span class="hljs-keyword">wait</span> a <span class="hljs-built_in">bit</span> <span class="hljs-built_in">time</span>.Sleep(<span class="hljs-number">2</span> * <span class="hljs-built_in">time</span>.Second) } }</pre></div><h2 id="000c">Handler and dispatcher</h2><p id="e562">We first need a struct to hold the list of events we want to listen to and which function to call whenever that event is transmitted. This struct also contains the channel used for communicating events.</p><div id="280d"><pre><span class="hljs-comment">// Create a struct to hold config</span> <span class="hljs-comment">// And simplify dependency injections</span> <span class="hljs-keyword">type</span> EventHandler <span class="hljs-keyword">struct</span> { <span class="hljs-comment">// Event channel</span> Events <span class="hljs-keyword">chan</span> Event <span class="hljs-comment">// hold the registedred event functionss</span> EventMap <span class="hljs-keyword">map</span>[EventType][]<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(Event)</span></span> }</pre></div><p id="aa6c">Next, we need to provide an initializing constructor for our <code>EventHandler</code>.</p><div id="a4ed"><pre><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewEventHandler</span><span class="hljs-params">()</span></span> *EventHandler { eventMap := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">map</span>[EventType][]<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(Event)</span></span>) event

Options

s := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> Event)</pre></div><div id="78bb"><pre> return <span class="hljs-variable">&</span>EventHandler<span class="hljs-punctuation">{</span> <span class="hljs-symbol"> Events:</span> events, <span class="hljs-symbol"> EventMap:</span> eventMap, <span class="hljs-punctuation">}</span> <span class="hljs-punctuation">}</span></pre></div><p id="98fe">Then, we can create our <code>Handle</code> function that associates the event with a callback function.</p><div id="308c"><pre><span class="hljs-comment">// register the handler function to handle an event type</span> func (h *EventHandler) <span class="hljs-built_in">Handle</span>(e EventType, f <span class="hljs-built_in">func</span>(Event)) { h<span class="hljs-selector-class">.EventMap</span><span class="hljs-selector-attr">[e]</span> = <span class="hljs-built_in">append</span>(h<span class="hljs-selector-class">.EventMap</span><span class="hljs-selector-attr">[e]</span>, f) }</pre></div><p id="e42a">Finally, we create the <code>EventDispatcher</code> function, the core of this mechanism. The <code>EventDispatcher</code>process any event sent to a channel, check its type, and if any function has been registering for that type, we call all registered functions.</p><div id="6597"><pre><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(h *EventHandler)</span></span> EventDispatcher() { <span class="hljs-keyword">for</span> evt := <span class="hljs-keyword">range</span> h.Events { log.Printf(<span class="hljs-string">"event recieved: %v"</span>, evt) <span class="hljs-keyword">if</span> handlers, ok := h.EventMap[evt.Type]; ok { <span class="hljs-comment">// If we registered an event</span> <span class="hljs-keyword">for</span> _, f := <span class="hljs-keyword">range</span> handlers { <span class="hljs-comment">// exacute function as goroutine</span> <span class="hljs-keyword">go</span> f(evt) } } } }</pre></div><h1 id="13e4">Using our system</h1><p id="4d4e">Everything is ready; we can start using our event handling system.</p><ol><li>Instantiate our event Handler</li><li>Register which event to listen to and what function to callback</li><li>Start the event sender</li><li>Start the event dispatcher</li></ol><div id="62ab"><pre><span class="hljs-keyword">func</span> <span class="hljs-title function_">main</span><span class="hljs-params">()</span> {</pre></div><div id="5b09"><pre> <span class="hljs-variable">eventHandler</span> := <span class="hljs-function"><span class="hljs-title">NewEventHandler</span>()</span></pre></div><div id="d244"><pre> eventHandler.Handle(event1, <span class="hljs-keyword">func</span><span class="hljs-params">()</span> { <span class="hljs-built_in">log</span>.Printf(<span class="hljs-string">"event Handled: %v"</span>, event1) })</pre></div><div id="5c56"><pre> <span class="hljs-variable">go</span> <span class="hljs-function"><span class="hljs-title">eventSender</span>(<span class="hljs-variable">eventHandler.Events</span>)</span></pre></div><div id="30f2"><pre> eventHandler<span class="hljs-selector-class">.EventDispatcher</span>()</pre></div><div id="9bf2"><pre>}</pre></div><p id="e590">The result should be along those lines:</p><figure id="5ee7"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*_D-GCRSu3K8CgTBXewJjJQ.gif"><figcaption></figcaption></figure><p id="19d6">Since we only handle an event of type <code>event1</code>, only <code>event1</code> shows as <code>Hansled</code>. All is good!</p><p id="d48a">The full code for this article can be found <a href="https://github.com/xNok/slack-go-demo-socketmode/blob/main/examples/middleware/main.go">here</a>.</p><h1 id="6f5e">Interesting Articles tackling the same topic</h1><ul><li><a href="https://drstearns.github.io/tutorials/gomiddleware/">Middleware Patterns in Go</a></li><li><a href="https://sathishvj.medium.com/web-handlers-and-middleware-in-golang-2706c2ecfb75">Web Handlers and Middleware in GoLang</a></li><li><a href="https://readmedium.com/lightweight-event-management-implemented-by-go-a654d59ac65">Lightweight event management implemented by Go</a></li><li><a href="https://readmedium.com/the-7-most-important-software-design-patterns-d60e546afb0e">The 7 Most Important Software Design Patterns</a></li></ul><p id="13e7"><i>Do you want <b>unlimited access</b> to all my content and many other writers’ content on Medium? Consider using my affiliate link to <a href="https://couedeloalexandre.medium.com/membership">become a Medium member today</a></i></p><h2 id="853a">Further reads</h2> <figure id="81d2"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://couedeloalexandre.medium.com/embed/list/3f9d03f2cb8f" allowfullscreen="" frameborder="0" height="184" width="undefined"> </div> </div> </figure></iframe></div></div></figure></article></body>

How I Turned Cleaning Into A Lifehack

And why it helps me stay happy and focused.

Photo by Sincerely Media on Unsplash

When I get up, I don’t always feel right. I spent years and years of my childhood and early adult life waking up shaking with nerves because of the day ahead in a school I hated.

That cloud above my head only really left me in the last couple of years, when I decided I’d had enough of it. However, habits die hard, and my body still remembers the physical effects of waking up anxious well, and sometimes, for no apparent reason, I still wake up with that lingering feeling.

So, I have to work every single morning at lifting my mood to ensure I have a good day, and that I go to bed happy and lessen the chances of waking up feeling nervous the next day. It’s hard work, but it gets easier over time, and it’s absolutely worth it

That’s why I have a really good morning routine. It starts with good coffee, reading my book, writing down my thoughts of the morning — good and bad, working on my articles, and spending a few minutes thinking about what I’m grateful for.

But I Also Love To Clean

No, I don’t mean I’m a sucker for degreasing the oven or cleaning the windows — although there is some pleasure in that.

I mean your everyday kind of maintenance of the home. I might just empty the dishwasher, wipe the kitchen counters, or fold some clean washing and stack it on the stairs ready to put away. It’s 5 AM when I get up every morning so what I choose to do has to be quiet enough that it won’t wake up my tornado toddler. I also clean throughout the day, as I go along.

Firstly, we need to keep our spaces hygienically clean for our physical health. We all know how food remnants can turn into vile bacteria that make us sick, or how lack of dusting can cause respiratory diseases. But I’m not going to give you a sermon about that because it won’t help you see cleaning as anything other than a chore.

I’m going to show you how the act of cleaning can boost your mental health, and how when it’s made into a lifehack, it can transform your wellbeing.

If You Don’t Care, It’s Because You’ve Forgotten How Good it Feels

Think about the science of your body make-up and the rest of the world. Think about the seasons, ecosystems and oceans. Think about how bees make honey. Think about how companies work. Think about factories, machinery, and computing. Think about how a pack of wolves work together to hunt down food, each having a specific role.

Everything in this world has structure, and it’s extremely well organised.

Think about the damage caused when something goes wrong. Think about the butterfly effect.

Chaos is confusing at best. It disorientates us. A natural disaster, for example, goes against the patterns we know so well and it causes a lot of impact not just to the area it happens in, but in the rest of the world.

So think about how such a seemingly irrelevant thing such as clutter and untidiness can affect your wellbeing at home, the place you spend the most time in.

When your safe place is chaotic, you’re going to feel more disorganised, unstructured, and scatty. You’re going to link those traits to your identity, when in actual fact, they’re changeable, and very easily so.

If you’re not used to being organised and living in a clean and tidy space, you might have simply forgotten how good it feels and how much of a difference it makes to your overall state of being.

It Helps You Focus

I don’t know about you, but I’m busy. Not only that, the fact I’m pregnant slows me down physically and my toddler son even more so. So I have to be extra organised to keep up with life.

Sometimes, I go through days constantly in a rush with the amount of shit I need to do. But when I put my son to bed and I sit down for the first time to relax in the evenings, I don’t feel stressed from the day, and I don’t feel dread for tomorrow’s goals.

Rather, I look around my house with pride because I still managed to keep the house clean and tidy. The fact I do it every day means it doesn’t take me long, and it isn’t energy-consuming. It allows me to focus on my actual goals, like my writing career.

Contrarily, if you live in a cluttered environment, you are more likely to feel overwhelmed by projects and lose your sense of focus.

An article in Psychology Today talks about how clutter can actually make it harder for people to concentrate. In 2011, researchers at the Princeton University of found that,

the visual cortex can be overwhelmed by task-irrelevant objects, making it harder to allocate attention and complete tasks efficiently.

So, it makes sense that a clean and clear space also helps to clear the mind and concentrate on the rest of your life.

If you’re like me, you like goals and you may have written down or mental to-do lists that you run through each day. It doesn’t matter how efficient you are at ticking them off, but you do start each day with a list. Most people do.

So when you get a couple of things done first thing in the morning, you feel great. Like you got ahead for the day. Combine that with a task that helps you be more organised at home, and you’ll get hooked on to that feeling of achievement.

Cleaning Solves Your Bigger Problems And Reduces Stress

Cleaning is easy. It requires virtually zero brainpower, and it is shown to be a stress reliever. In fact,

a study by the University of Connecticut found that in times of high stress, people default to repetitive behaviors like cleaning because it gives them a sense of control during a chaotic time. — Verywellmind

When you have an ongoing issue to solve and you’re wracking your brains with it, it’s good to get step out of the room and give yourself a little time to focus on something else.

Some people might blow off some steam at the gym. Some might work on their car, or paint. I don’t get much time to myself other than at 5 AM, and I’m also 6 months pregnant, so I write, and I clean.

I solve a smaller problem — like the limescale build up in the sink in the bathroom, while I think about how I’m going to get unstuck on an article.

Not only that but physically seeing the results of a cleaner environment plays a part in feeling more relaxed. A 2010 study by researchers at the University of California used software to analyse how 30 cohabiting couples talked about their homes:

Those describing their living spaces as “cluttered” or complained of “unfinished projects” were more likely to be suffering from depression and fatigue than those who described their homes as “restful” and “restorative.” It was also found that those living in cluttered environments displayed higher levels of cortisol.

Cortisol is our stress hormone. To feel added levels of stress simply because of your untidy or cluttered home is completely unnecessary — especially when you have so much more stuff to be stressed about, such as your job, finances, politics, etc.

Photo by The Anam on Unsplash

You need to let off some steam now and again. Some people might go for a massage. I go get my nails done every 3 weeks. You might do an entire spa day or play golf with a friend every month.

But I don’t think many would consider cleaning as a form of relaxation because it’s seen as a neverending chore.

When viewed as a stress-reliever, however, you have unlocked a really easy, cheap, and powerful way to clear your mind. Put some music on while you’re doing it, and you’ll feel on top of the world.

Cleaning relieves tension in the muscles. It exercises them. Not only does this release the same endorphins as when you exercise, helping you to feel pumped, but it brings the feeling of accomplishment once you’ve finished.

It’s looking at a space with pride and a little more love.

You can go from hating your home to loving it just by spending a little time each day tidying up or actually spring cleaning it every so often. And when you change your immediate surroundings, you’re helping to change the way you look at your circumstances.

Do you still see cleaning as a chore, or as a habit we should all cultivate to boost some self-love?

Takeaway

Photo by JESHOOTS.COM on Unsplash

Because I spend a little time cleaning every day, I don’t often have to do the huge cleaning sprees that some might. I don’t let things accumulate to the point I dread taking care of them.

It takes me 10 minutes to scrub the bathroom clean because I do it every week. I mop the floors once every 3 days unless my son makes a mess, which he quite often does. My laundry basket is more often than not empty because I don’t think twice when clothes need washing. I just do it.

I’m not showing off — I’m saying that no matter how hectic your life is, keeping your home clean and tidy is doable, and in fact, it will help tone down the chaos of the rest of your life.

If you aren’t feeling good and you’ve tried a million life-changing ways to boost your morale, consider cleaning. If you already do so, consider cleaning mindfully. The act of thinking about the task you’re doing brings grounds you to the present moment. Notice as the dust is lifted, as the watermarks on your shower door disappear, and as the space on your counter clears when you put things away.

When you concentrate on the cleaning itself and you focus on the results it brings, you will feel better. Do this throughout the day, and the rest of your goals will be much easier to take care of.

It’s so simple, yet life-changing.

Sylvia Emokpae, thinker and philosopher, is passionate about self-love and motherhood. See more work like this.

Follow her on Twitter.

Health
Mental Health
Self Improvement
Self Growth
Lifehacks
Recommended from ReadMedium