Skip to content
Snippets Groups Projects

Resolve "Application that allows to access events through websocket"

All threads resolved!
8 files
+ 233
11
Compare changes
  • Side-by-side
  • Inline
Files
8
+ 62
0
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",
Addrs: []string{"localhost:80"},
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)
}
Loading