Skip to content

Commit

Permalink
add examples
Browse files Browse the repository at this point in the history
agoalofalife committed Nov 14, 2017
1 parent b95ff88 commit aa3053e
Showing 3 changed files with 128 additions and 0 deletions.
30 changes: 30 additions & 0 deletions examples/base_server.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
72 changes: 72 additions & 0 deletions examples/event_and_channels.go
Original file line number Diff line number Diff line change
@@ -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
}
}
}
26 changes: 26 additions & 0 deletions examples/one_to_many.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit aa3053e

Please sign in to comment.