realtimetraffic/realtimetrafficd/main.go

94 lines
2.2 KiB
Go
Raw Normal View History

2014-03-09 16:53:21 +01:00
/*
2017-05-22 14:58:47 +02:00
* Copyright (C) 2014-2017 struktur AG
2014-03-09 16:53:21 +01:00
* http://www.strukturag.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2017-05-22 14:58:47 +02:00
2014-03-09 16:53:21 +01:00
package main
import (
"flag"
2017-05-23 15:08:54 +02:00
"fmt"
2014-03-09 16:53:21 +01:00
"log"
"net/http"
2017-05-23 15:08:54 +02:00
"runtime"
"github.com/longsleep/realtimetraffic/client"
"github.com/gorilla/websocket"
2014-03-09 16:53:21 +01:00
)
func serveClient(w http.ResponseWriter, r *http.Request) {
2017-05-22 16:12:18 +02:00
if r.Method != "GET" && r.Method != "HEAD" {
http.Error(w, "Method nod allowed", 405)
2014-03-09 16:53:21 +01:00
return
}
http.StripPrefix("/", client.HandlerFunc).ServeHTTP(w, r)
}
func serveWs(w http.ResponseWriter, r *http.Request) {
2014-03-09 16:53:21 +01:00
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
2014-03-09 16:53:21 +01:00
return
}
// Read request details.
r.ParseForm()
iface := r.FormValue("if")
if iface == "" {
iface = "eth0"
}
ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
if _, ok := err.(websocket.HandshakeError); ok {
http.Error(w, "Not a websocket handshake", 400)
return
} else if err != nil {
log.Println(err)
return
2014-03-09 16:53:21 +01:00
}
c := &connection{send: make(chan []byte, 256), ws: ws, iface: iface}
h.register <- c
go c.writePump()
c.readPump()
2014-03-09 16:53:21 +01:00
}
func main() {
var err error
2017-05-23 15:08:54 +02:00
listenAddr := flag.String("listen", "127.0.0.1:8088", "Listen address.")
versionFlag := flag.Bool("version", false, "Version")
2014-03-09 16:53:21 +01:00
flag.Parse()
2017-05-23 15:08:54 +02:00
if *versionFlag {
fmt.Println("Version :", Version)
fmt.Println("Build time :", BuildStamp)
fmt.Println("Go :", runtime.Version())
return
}
2014-03-09 16:53:21 +01:00
go h.run()
http.HandleFunc("/", serveClient)
http.HandleFunc("/realtimetraffic", serveWs)
2017-05-23 15:08:54 +02:00
log.Printf("starting realtimetrafficd %s on %sn", Version, *listenAddr)
err = http.ListenAndServe(*listenAddr, nil)
2014-03-09 16:53:21 +01:00
if err != nil {
2017-05-23 15:08:54 +02:00
log.Fatal(err.Error())
2014-03-09 16:53:21 +01:00
}
2017-05-23 15:08:54 +02:00
defer log.Println("exiting")
2014-03-09 16:53:21 +01:00
}