go-dispatcher
A single-file dispatcher written in Golang.
Description
Inspired by the JSON-RPC module of polygon-edge and geth, this package provides a way to register methods from a struct pointer.
It can be used to bootstrap a server or create a worker pool in your project !
Installation
Run the following command :
go get github.com/PtitLuca/[email protected]
Quick Start
A very simple example
package main
import (
"fmt"
"github.com/PtitLuca/go-dispatcher/dispatcher"
"log"
)
type T struct {
}
func (t *T) Example(a, b int) int {
return a + b
}
func main() {
d := dispatcher.New()
err := d.Register("Test", &T{})
if err != nil {
log.Fatalln(err)
}
output, err := d.Run("Test", "Example", 1, 2)
if err != nil {
log.Fatalln(err)
}
fmt.Println(output[0].Int())
}
After running, you should get this in your terminal :
3
Multi-service registration
package main
import (
"fmt"
"github.com/PtitLuca/go-dispatcher/dispatcher"
"log"
)
type X struct {
}
func (x *X) Example2(a, b string) string {
return a + b
}
type T struct {
}
func (t *T) Example(a, b int) int {
return a + b
}
func main() {
d := dispatcher.New()
err := d.Register("Test", &T{})
if err != nil {
log.Fatalln(err)
}
err = d.Register("TestX", &X{})
if err != nil {
log.Fatalln(err)
}
output, err := d.Run("Test", "Example", 1, 2)
if err != nil {
log.Fatalln(err)
}
fmt.Println(output[0].Int())
output, err = d.Run("TestX", "Example2", "Hello", "World")
if err != nil {
log.Fatalln(err)
}
fmt.Println(output[0].String())
}
After running, you should get this in your terminal :
3
HelloWorld
Variadic arguments
package main
import (
"fmt"
"github.com/PtitLuca/go-dispatcher/dispatcher"
"log"
)
type T struct {
}
func (t *T) ExampleVariadic(a int, b ...string) int {
return a + len(b)
}
func main() {
d := dispatcher.New()
err := d.Register("Test", &T{})
if err != nil {
log.Fatalln(err)
}
output, err := d.Run("Test", "ExampleVariadic", 1, "These", "Are", "Variadic", "Arguments")
if err != nil {
log.Fatalln(err)
}
fmt.Println(output[0].Int())
}
After running, you should get this in your terminal :
5
Features
This package has support for :
- Multi-service registration
- Methods registration - exported only
- Variadic arguments