This repository has been archived by the owner on May 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
75 lines (60 loc) · 1.91 KB
/
main.go
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"flag"
"github.com/flachnetz/flatnet-webui/flatnet"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"io/ioutil"
"log"
"net/http"
"os"
)
func handleWebSocket(hub *flatnet.Hub, w http.ResponseWriter, req *http.Request) {
socket, err := websocket.Upgrade(w, req, nil, 0, 0)
if err != nil {
log.Println("Could not upgrade to websocket: ", err)
return
}
hub.HandleConnection(socket)
}
func handleHttpTrafficSource(hub *flatnet.Hub, w http.ResponseWriter, req *http.Request) {
bytes, err := ioutil.ReadAll(req.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
hub.Broadcast(bytes)
w.WriteHeader(http.StatusNoContent)
}
func main() {
port := flag.String("listen", ":8080", "Address to use for creating the http server.")
kafkaAddress := flag.String("kafka", "", "Address of kafka broker.")
kafkaTopic := flag.String("kafka-topic", "flowly", "Name of the kafka topic to consume.")
dummy := flag.Bool("dummy", false, "Generate dummy traffic")
flag.Parse()
// create the hub and start routing traffic.
hub := flatnet.NewHub()
go hub.MainLoop()
if *dummy {
log.Println("Starting dummy traffic generator")
flatnet.SetupDummyTraffic(hub)
}
if *kafkaAddress != "" {
if *kafkaTopic == "" {
log.Fatalln("You need to specify --kafka-topic with --kafka-address")
}
flatnet.SetupKafkaTraffic(hub, *kafkaAddress, *kafkaTopic)
}
router := mux.NewRouter()
router.Path("/traffic").Methods("GET").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
handleWebSocket(hub, w, req)
})
router.Path("/traffic").Methods("POST").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
handleHttpTrafficSource(hub, w, req)
})
router.PathPrefix("/").Handler(http.FileServer(http.Dir("static")))
panic(http.ListenAndServe(*port,
handlers.LoggingHandler(os.Stdout,
handlers.RecoveryHandler()(router))))
}