package web import ( "net" "net/http" "github.com/NYTimes/gziphandler" "github.com/bdlm/log" "dev.sum7.eu/genofire/golang-lib/database" lib "dev.sum7.eu/genofire/golang-lib/http" "dev.sum7.eu/genofire/golang-lib/websocket" "dev.sum7.eu/genofire/wifictld-analyzer/capture" "dev.sum7.eu/genofire/wifictld-analyzer/data" ) type Server struct { web *http.Server ws *websocket.WebsocketHandlerService } // New creates a new webserver and starts it func New(config *Config) *Server { ws := websocket.NewWebsocketHandlerService() ws.Listen("/ws") http.HandleFunc("/data.json", func(w http.ResponseWriter, r *http.Request) { type dataResponse struct { APs []data.AP `json:"aps"` Clients []data.Client `json:"clients"` } data := &dataResponse{} if result := database.Read.Find(&data.APs); result.Error != nil { log.WithField("error", result.Error.Error()).Warn("not possible to read APs") http.Error(w, "not possible to read APs", http.StatusNotFound) return } if result := database.Read.Find(&data.Clients); result.Error != nil { log.WithField("error", result.Error.Error()).Warn("not possible to read Clients") http.Error(w, "not possible to read Clients", http.StatusNotFound) return } lib.Write(w, data) log.Info("fetch data") }) http.Handle("/", gziphandler.GzipHandler(http.FileServer(http.Dir(config.Webroot)))) return &Server{ web: &http.Server{ Addr: config.Bind, }, ws: ws, } } func (srv *Server) Handler(addr *net.UDPAddr, msg *capture.SocketMSG) (*capture.SocketMSG, error) { srv.ws.SendAll(&websocket.Message{ Subject: "wifictld_pkg", Body: map[string]interface{}{ "ip": addr.IP, "msg": msg, }, }) return msg, nil } func (srv *Server) Start() { // service connections if err := srv.web.ListenAndServe(); err != http.ErrServerClosed { log.Panicf("webserver crashed: %s", err) } } func (srv *Server) Close() { srv.web.Close() srv.ws.Close() }