Minimalistic, pluggable Golang evloop/timer handler with dependency-injection

Anagent Build Status codecov Go Report Card godoc

Minimalistic, pluggable Golang evloop/timer handler with dependency-injection - based on codegangsta/inject - go-macaron/inject and chuckpreslar/emission.

Anagent is a lightweight library that allows you to plug inside to other event loops, or allows you to handle and create your own within your application - leaving the control to you.

It comes with dependency-injection from codegangsta/inject, and it's also a soft-wrapper to chuckpreslar/emission, adding to it dependency injection capabilities and timer handlers.

Usage

Event Emitter with Dependency injection

    package main

    import (
    	"log"
    	"github.com/mudler/anagent"
    )

    type TestTest struct {
    	Test string
    }

    func main() {
    	agent := anagent.New()
    	mytest := &TestTest{Test: "PONG!"}
    	agent.Map(mytest)

    	agent.Once("test", func(te *TestTest, l *log.Logger) {
    		if te.Test == "PONG!" {
    			l.Println("It just works!")
    		}
    	})

    	agent.Emit("test")
    }

What happened here? we mapped our structure instance (TestTest) inside the agent with (agent.Map()), and all fired events can access to them.

Timer / Reactor

    package main

    import "github.com/mudler/anagent"
    import "fmt"

    type TestTest struct {
            Test string
    }

    func main() {
            agent := anagent.New()
            mytest := &TestTest{Test: "PONG!"}
            agent.Map(mytest)

            agent.Emitter().On("test", func(s string) { fmt.Println("Received: " + s) })

            // Not recurring timer
            agent.TimerSeconds(int64(3), false, func(a *anagent.Anagent, te *TestTest) {
                    a.Emitter().Emit("test", te.Test)
                    go a.Stop()
            })

            agent.Start() // Loops here and never returns
    }

The code portion will start and wait for 3 seconds, then it will execute the callback (not recurring, that's why the false) that will fire a custom event defined before (note, it's not using the dependency-injection capabilities, thus it's accessing the emitter handler directly with agent.Emitter()).

The difference is that when we access to On() provided by agent.On(), we access to the agent dependencies, that have been mapped with agent.Map() - otherwise, with agent.Emitter().On() we are free to bind any arguments to the event callback.

After the event is fired, the timer stops the eventloop (a.Stop()), so the program returns.

Hook into other loops

It is often in other framework to use loop patterns, as example in framework for game development, network agents, and such. We can hook into other loops, and run the agent Step function, so we can still leverage the evloop functionalities.

    package main

    import "github.com/mudler/anagent"
    import "fmt"

    type TestTest struct {
    	Test string
    }

    func main() {
    	agent := anagent.New()
    	mytest := &TestTest{Test: "PONG!"}
    	agent.Map(mytest)

        // Reply with a delay of 2s
    	agent.Emitter().On("test", func(s string) {
    		agent.TimerSeconds(int64(2), false, func() {
    			fmt.Println("Received: " + s)
    		})
    	})

    	// Recurring timer
    	agent.TimerSeconds(int64(3), true, func(a *anagent.Anagent, te *TestTest) {
    		fmt.Println("PING!")
    		a.Emitter().Emit("test", te.Test)
    	})

    	for { // Infinite loop
    		agent.Step()
    	}
    }
Owner
Similar Resources

a generic object pool for golang

Go Commons Pool The Go Commons Pool is a generic object pool for Golang, direct rewrite from Apache Commons Pool. Features Support custom PooledObject

Jan 5, 2023

Resiliency patterns for golang

go-resiliency Resiliency patterns for golang. Based in part on Hystrix, Semian, and others. Currently implemented patterns include: circuit-breaker (i

Jan 3, 2023

psutil for golang

gopsutil: psutil for golang This is a port of psutil (https://github.com/giampaolo/psutil). The challenge is porting all psutil functions on some arch

Jan 2, 2023

Type-safe Prometheus metrics builder library for golang

gotoprom A Prometheus metrics builder gotoprom offers an easy to use declarative API with type-safe labels for building and using Prometheus metrics.

Dec 5, 2022

Simple licensing library for golang.

license-key A simple licensing library in Golang, that generates license files containing arbitrary data. Note that this implementation is quite basic

Dec 24, 2022

Some utilities for Persian language in Go (Golang)

persian Some utilities for Persian language in Go (Golang). Installation go get github.com/mavihq/persian API .ToPersianDigits Converts all English d

Oct 22, 2022

A Golang library to manipulate strings according to the word parsing rules of the UNIX Bourne shell.

shellwords A Golang library to manipulate strings according to the word parsing rules of the UNIX Bourne shell. Installation go get github.com/Wing924

Sep 27, 2022

A golang URL Shortener

url-shortener A golang URL Shortener with mysql support. Using Bijective conversion between natural numbers (IDs) and short strings Installation Using

Dec 10, 2022

:guardsman: A teeny tiny and somewhat opinionated generator for your next golang project

A Yeoman Golang Generator We are very sorry Gophers, but other names for the generator where taken, so we choose go-lang. But we have gocreate as an a

Sep 27, 2022
A minimalistic message queue server, in Go

lineup, a tiny queue server lineup is a very simple queue server. all it does is serve a binary-safe priority queue with a simple protocol insp

Aug 17, 2022
Provide Go Statistics Handler, Struct, Measure Method

Go Statistics Handler About The gosh is an abbreviation for Go Statistics Handler. This Repository is provided following functions. Go runtime statist

Jan 8, 2023
go.mod file is the root of dependency management in Go

go.mod file is the root of dependency management in Go. All the modules which are needed or to be used in the project are maintained in go.mod file. I

Feb 9, 2022
Golang CS:GO external base. Development currently halted due to compiler/runtime Golang bugs.

gogo Golang CS:GO External cheat/base. Also, my first Golang project. Wait! Development momentarily halted due to compiler/runtime bugs. Disclaimer Th

Jun 25, 2022
Belajar Golang Install Golang

Golang belajar Golang Install Golang = download di https://golang.org/dl/ = pilih yg Zip = extract file zipnya = buka foldernya - copy folder go = pas

Nov 15, 2021
Golang-module-references - A reference for how to setup a Golang project with modules - Task Management + Math Examples

Golang Module Project The purpose of this project is to act as a reference for setting up future Golang projects using modules. This project has a mat

Jan 2, 2022
Golang-echo-sample - Make an out-of-the-box backend based on golang-echo

Golang-echo-sample - Make an out-of-the-box backend based on golang-echo

Dec 31, 2021
GoLang Library for Browser Capabilities Project

Browser Capabilities GoLang Project PHP has get_browser() function which tells what the user's browser is capable of. You can check original documenta

Sep 27, 2022
Golang counters for readers/writers

Datacounter Golang counters for readers/writers. Examples ReaderCounter buf := bytes.Buffer{} buf.Write(data) counter := datacounter.NewReaderCounter(

Oct 9, 2022
Golang beautify data display for Humans

Golang beautify data display for Humans English 简体中文 Install # Stable version go get -u -v gopkg.in/ffmt.v1 # Latest version go get -u -v github.com/

Dec 22, 2022