avatarILLUMINATION-Curators

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>

Curated Collection

Curated Book Chapters of Illumination #01

Introduction to published authors and sample book chapters on Illumination Book Chapters publication on Medium

Photo by Yaroslav Shuraev on Pexels

Dear Readers and Writers,

First, let me briefly introduce the Illumination Book Chapters publication on Medium. This unique publication was established by Dr Mehmet Yildiz in March 2021 and announced on the first birthday of Illumination.

Since then, many published authors have shared their book chapters. Within a year, 100+ authors contributed to this publication. The publication serves both traditionally published and independent authors aiming to monetize content in story format on Medium.

As an editor, content curator, author, and book lover, my goal is to create an awareness of the work of these authors by selecting one chapter from their books.

Dr Mehmet Yildiz, owner and chief editor of Illumination Integrated Publications, encouraged me to undertake this duty as he understands the requirements and pain points published authors’ have in the market.

Dr. Yildiz has empathy and compassion for authors as he is also a published author. He developed a system to raise profiles of authors, increase collaboration among creators and readers, and create visibility for their content.

To gain better visibility on Medium, our editorial team suggests that authors index book chapters and submit them in a story format to our other publications like ILLUMINATION, ILLUMINATION-Curated, ILLUMINATION’S MIRROR, ILLUMINATION on YouTube, Technology Hits, SYNERGY, and Readers Hope.

You may also share links to the chapters and indexes of your books at ILLUMINATION Slack Workspace in the channel called #post-your-own-writing-here.

I look forward to reading and promoting your books. We’d appreciate the feedback of our readers.

Sample Book Chapter By Authors

Image courtesy of Dr Mehmet Yildizdigitalmehmet.com

Dr Mehmet Yildiz

On the Cusp of the Artificial Intelligence Revolution — Preface

The Power of Digital Affiliate Marketing -Chapter 1

A Modern Enterprise Architecture Approach — Chapter 1

Summary Of “Digital Intelligence”

Powerful Life-Changing Hacks That Truly Transformed My Life —

Arlo Hennings, Ph.D.

Traveling the World in Search of Drug-Free Cures

Bali: Life on the Ring of Fire (series)

Meet Arlo Hennings, PhD on Illumination YouTube Channel by ILLUMINATION and Illumination YouTube Coordinator

Carla Woody

Standing Stark: The Willingness to Engage

Calling Our Spirits Home: Gateways to Full Consciousness

Portals to the Vision Serpent

Meet Carla Woody on Illumination YouTube Channel by ILLUMINATION and Illumination YouTube Coordinator

Shashi Sastry

Book: Philosophy of Life Instinct:

Meet Shashi Sastry on YouTube by ILLUMINATION and Illumination YouTube Coordinator

Tom Hanratty

The Wicked Affair of the Golden Emperor

Kaya and the Eater of Bones

Phil Rossi

Soldier Hill — Chapter 5 —

Background Acting 101: Chapters 1–10 —

Make Customer Service an Outlier Not an Outpost (Part 3) —

Ulf Wolf

Garbo’s Faces

The Zen of Calories

Curiosity

Francesco Rizzuto

The Naked Girl (La Niña Desnuda) — Chapter 15

Virgin Quartet

he Cranesbill

Laurie Weiss, PhD

Reconnect to Rescue Your Marriage Chapter 14

Lady Dr. Gabriella Korosi

Debt And Consumerism

Britta Ollrogge, MBA

Everything Flows: Use Personal Kanban And Get Things Right — Chapter 13

Toni Crowe

Never A $7 Whore

From Zero to Family Hero

Regina Clarke

Voices from the Old Earth

Tales of Mist and Magic

Robert Shaneyfelt

West Coast Beach

Old Alton Bridge

bakagaijin

We Build the Berlin Wall

Old Bones and Ghosts

Keri Mangis

Annelise Lords

The Yellow Hibiscus Chapter 70

Kevin Miller

Know Power, Know Responsibility: How to unleash the potential of every child in America

Janet Stilson

The Juice: Charisma Is a SuperPower In This Tale of Suspense and Romance

Josephine Crispin

Midnyte Madness: A Tale of Two Terrors

Claudia Stack

Willow Chapter 4: Maggie Arrives

Angelina Der Arakelian

A Timeless Speck on a Timed Venture

A One Way Ticket to Everywhere

Blurred Fate

Simon Dillon

Spectre of Springwell Forest Chapter 1

Peaceful Quiet Lives

Warren Brown

Laura Attraction- Chapter 2

Pandemic Blasters- Chapter 3

Monkey in Mind- Chapter 3

Paula Shablo

Starting In The Middle of The End

Brian Feutz

Jinx, a Novel: Chapter One

Harry Hogg

Bart — Born On A London Bus

Magnus Oceanic Part 2

Juergen K. Tossmann

When Kennedy Went To Berlin

Abandonment Wounds

Julian Cosky

Chapter 3 — My First Visit

mallory james

Life

A New Job

Martine Weber

Aymma’s Quest

A burnished throne

Neil Mapes

Jorge Chavez and Lima

Nazca via inane Ica

Pam Saraga

Amazon Diet

Rebecca Stevens A.

People Have Signed A Petition For Will Smith And Jada Pinkett Smith To Shut Up

Ryan Klemek

Black Iris: Chapter Six

Francine Fallara

Inkling Whispers: eNd Me I — Shooting Stars Swaying Darkness

Custody to My Soul

Frank Ontario

The Slide: Chapter 14 | Secrets and Love, the past (continued)

Agnes Laurens

Mystery Letter: In The Library

The Mystery Letter

Aza Y. Alam

Let Our Angry Passion, Liberate! Chapter 1

Message in Time

1. If Light is in Your Heart

White Rule(s) and ‘Little’ White Lies — What Has Changed?

Brian Loo Soon Hua

The World’s Worst Swear Words: Chapter 3

Britni Pepper

Send Lawyers, Guns, and Money

Get High in Turkey

Charles Laramie

The Therapist Chapter 7

Christopher Akinlade

While She Was Away — Chapter 4

Darcy Thiel

Bitter & Sweet; A Family’s Journey With Cancer

Deena Thomson

Poppies- Chapter 33-

Floyd Mori

The Japanese American Story…Part 15

Gregory Reece-Smith

The Seven Secrets to Living in Harmony — Secret #5 Answers The Question “Why do I have trouble…

Harry Seitz

There Are Days That I’ll Remember

Iron Manimal: Chapter 4

Heather C Holmes

By the Grace of God: Chapter 9

My Little Shadow: Chapter 1

Jacquelyn Lynn

The Value of Creativity

Work as Worship

Jair Ribeiro

Introduction to A.I., Robotics, and Coding (for Parents)

The Terminator paradox — How…

Jason Ward

Haunted Thailand — A Brief Introduction

John Cunningham

How to Love, Value & Respect Yourself

Developing Self-Love

John Ross

Lovers: a book of poems

Josie Elbiry

The God of a Missing Idolatry

Malaria is Not as Scary as Crystal Methamphetamine

Julie Nyhus MSN, FNP-BC

Making the Cut — Part 1: I Don’t Believe in God

Making the Cut — Part 2: A Seamless Connection

Karen Madej

Groped in the Park

Sarah Befriends the Spiked Bowl of Punch

Liam Ireland

The Sex and Colour of Justice

The Office Part 1

Linda Acaster

Contribution to Mankind and Other Stories of the Dark

Lisa Gerard Braun

She Is Not a Duck, Part 14

Maria Rattray

Outsmarted: Early Chapters

In The Name Of My Father: Chapter 32

In The Name Of My Father — All chapters Indexed by Dr Mehmet Yildiz

Marjorie J McDonald

Finch Ownership — Chapter 1

Mia Hayes

The Secrets We Keep

Nicole Maharaj

Inheritance of Death: The Turning of the Tide

Where few fear to tread: Chapter Eleven

Niru

Dares, Drama and Deception

365 Days of F(ib)B-ing: Chapter 1

Øivind H. Solheim

A Dystopian Novel from the Cold War

The Old Factory on the River Plain

Phil Truman

Skins Game, Part 2

Murders of the Sixth Kind — Ch. 3

Ruby Lee

The Haunted Mansion Mystery

The Marriage Wars

A.H. Mehr

Acne Adventures — Lessons Learnt

Carol McClain Craver

CraverShadows — Chapter Three

Sridhar Pai Tonse

The Genesis and Journey of Thought

S.W. Lauden

That’ll Be The Day

Carol Price

Out of Broken Mirrors

Tom McLaughlin

Life is not a Lemon

Tree Langdon

We Learned a Lesson the Hard Way

Trista Signe Ainsworth

Opening Your Heart To More

Wry Welwood

A Victor’s Psalm — Chapter 2

TJ Larson

The Chaos Mandate

The Hello Kitty System

Enchanted Luciferse Chapter 1A

Sakari Lacross

How Long Is Forever

Arcane

Erwin Lima

The value of Purpose and Storytelling

Avana Lilly

Mystery Cove

Akarsh Nalawade

Beamish And Bhaji

John D. Leavy

The Role of a Book’s Foreword

We thank the reader for reading these book chapters and writers for their contributions.

Sample Curated Collections

Curated Collection by ILLUMINATION-Curator

You may check my previous collections from this link

Curated Collections by ILLUMINATION

Curated Collection #112

You can find featured stories by ILLUMINATION in 2022 from this meta collection. We appreciate the support of our chief editor, Dr Mehmet Yildiz, in creating and promote these collections.

Meta Collection of Featured Stories

Curated Collections by Technology Hits

Hand-Picked Articles #81

Hand-Picked Book Chapters #01

Collection of Hand Picked Articles

Thank you for reviewing our collections. We hope you find some valuable pieces.

Essential Resources for Writers

Onboarding Pack for New Writers

Publication Resources

Essential publication related stories can be accessed via this collection.

Meet Writers from Their Pen

Meet Editors of Our Publications

Join Illumination Fiction Club

Publications of Our Writers on Medium

Invitation to Potential Writers

To join our vibrant and supportive publications on Medium, please send a request via this link. We will help you gain visibility and succeed as a writer on Medium. Please point out the publication name with your Medium account ID in the request. If you are new to Medium, you can join via this link.

Readers can read thousands of stories, and writers can monetize self-published content.

Writing
Reading
Books
Books And Authors
Authors
Recommended from ReadMedium