diff --git a/examples/base_server.go b/examples/base_server.go new file mode 100644 index 0000000..ec71e32 --- /dev/null +++ b/examples/base_server.go @@ -0,0 +1,30 @@ +package examples + +import ( + "github.com/agoalofalife/event" + "net/http" + "strconv" +) + +func baseServer() { + e := event.New() + + type CounterPing int + var count CounterPing + + e.Add(count, func() { count += 1 }) + + http.HandleFunc("/ping", func(writer http.ResponseWriter, request *http.Request) { + e.Fire(count) + writer.WriteHeader(http.StatusCreated) + }) + + http.HandleFunc("/count", func(writer http.ResponseWriter, request *http.Request) { + writer.Write([]byte(strconv.Itoa(int(count)))) + }) + + err := http.ListenAndServe(":3000", nil) + if err != nil { + panic(err) + } +} diff --git a/examples/event_and_channels.go b/examples/event_and_channels.go new file mode 100644 index 0000000..c0adc19 --- /dev/null +++ b/examples/event_and_channels.go @@ -0,0 +1,72 @@ +package examples + +import ( + "fmt" + "github.com/agoalofalife/event" + "math/rand" + "time" +) + +type Getter interface { + Get(msg string) +} + +type WareHouse struct{} + +func (w WareHouse) Get(msg string) { + fmt.Printf("there is a new message : '%s' in warehouse\n", msg) +} + +type Office struct{} + +func (o Office) Get(msg string) { + fmt.Printf("there is a new message : '%s' in office\n", msg) +} + +func eventAndChallels() { + e := event.New() + var message = make(chan string) + eventer := new(Getter) + wareHouse := new(WareHouse) + office := new(Office) + + e.Add(eventer, wareHouse.Get) + e.Add(eventer, office.Get) + + go recipient(e, message, eventer) + go sender(message) + // + time.Sleep(time.Second * 11) +} +func recipient(e *event.Dispatcher, message <-chan string, name *Getter) { + for { + select { + case msg := <-message: + if msg != "" { + e.Go(name, msg) + } else { + break + } + } + } +} +func sender(message chan<- string) { + timeLimit := time.Now().Add(time.Second * 10) + cases := []string{ + "Received a new order", + "Came shipping", + "Message from telegram", + } + + for { + time.Sleep(time.Second * 2) + if time.Now().Sub(timeLimit) < 0 { + message <- cases[rand.Intn(len(cases))] + } else { + fmt.Println("Stop") + time.Sleep(time.Second * 2) + close(message) + break + } + } +} diff --git a/examples/one_to_many.go b/examples/one_to_many.go new file mode 100644 index 0000000..85ea283 --- /dev/null +++ b/examples/one_to_many.go @@ -0,0 +1,26 @@ +package examples + +import ( + "github.com/agoalofalife/event" + "fmt" +) + +func oneToMany() { + e := event.New() + + e.Add("receiving.message", func() { + fmt.Println("Post email") + }) + + e.Add("receiving.message", func() { + fmt.Println("Post in chat") + }) + e.Add("receiving.message", func() { + fmt.Println("Create task") + }) + + e.Go("receiving.message") + //Post email + //Post in chat + //Create task +}