Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"code.fbi.h-da.de/danet/gosdn/application-framework/event"
"github.com/lesismal/nbio/nbhttp"
"github.com/sirupsen/logrus"
)
// Application is an example for a sdn application.
type Application struct {
eventService event.ServiceInterface
stopChannel chan os.Signal
}
// Run runs the application.
func (a *Application) Run() {
signal.Notify(a.stopChannel, os.Interrupt, syscall.SIGTERM)
a.eventService.SubscribeToEventType([]event.TypeToCallbackTuple{
{Type: event.Add, Callback: a.callback},
{Type: event.Delete, Callback: a.callback},
{Type: event.Update, Callback: a.callback},
})
a.eventService.SetupEventReciever(a.stopChannel)
mux := &http.ServeMux{}
mux.HandleFunc("/events", onWebsocket)
svr := nbhttp.NewServer(nbhttp.Config{
Network: "tcp",
Handler: mux,
})
err := svr.Start()
if err != nil {
fmt.Printf("Server start failed: %v\n", err)
return
}
<-a.stopChannel
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
svr.Shutdown(ctx)
}
func (a *Application) callback(event *event.Event) {
b, err := json.Marshal(event)
if err != nil {
logrus.Error("Failed marshal of event")
}
clientManager.Publish(b)
}