logmania/api/receive/main.go

93 lines
1.9 KiB
Go
Raw Normal View History

2017-06-13 00:39:12 +02:00
// receiver of log entry over network (websocket)
package receive
2017-06-12 22:32:27 +02:00
import (
"encoding/json"
"net/http"
2017-06-16 10:33:35 +02:00
"github.com/gorilla/websocket"
2017-06-12 22:32:27 +02:00
"github.com/genofire/logmania/database"
"github.com/genofire/logmania/log"
2017-06-16 10:33:35 +02:00
"github.com/genofire/logmania/notify"
2017-06-24 13:17:47 +02:00
logOutput "github.com/genofire/logmania/log/hook/output"
2017-06-12 22:32:27 +02:00
)
2017-06-13 00:21:19 +02:00
// http.Handler for init network
2017-06-12 22:32:27 +02:00
type Handler struct {
2017-06-13 00:21:19 +02:00
http.Handler
2017-06-12 22:32:27 +02:00
upgrader websocket.Upgrader
2017-06-16 10:33:35 +02:00
Notify notify.Notifier
2017-06-12 22:32:27 +02:00
}
2017-06-13 00:21:19 +02:00
// init new Handler
2017-06-16 10:33:35 +02:00
func NewHandler(notifyHandler notify.Notifier) *Handler {
2017-06-12 22:32:27 +02:00
return &Handler{
upgrader: websocket.Upgrader{},
2017-06-16 10:33:35 +02:00
Notify: notifyHandler,
2017-06-12 22:32:27 +02:00
}
}
2017-06-13 00:21:19 +02:00
// server response of handler
2017-06-12 22:32:27 +02:00
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logEntry := log.HTTP(r)
c, err := h.upgrader.Upgrade(w, r, nil)
if err != nil {
logEntry.Warn("no webservice upgrade:", err)
return
}
token := ""
defer c.Close()
for {
if token == "" {
var maybeToken string
msgType, msg, err := c.ReadMessage()
if err != nil {
2017-06-13 00:39:12 +02:00
logEntry.Error("receiving token", err)
2017-06-12 22:32:27 +02:00
break
}
if msgType != websocket.TextMessage {
2017-06-13 00:39:12 +02:00
logEntry.Warn("receive no token")
2017-06-12 22:32:27 +02:00
break
}
maybeToken = string(msg)
logEntry.AddField("token", maybeToken)
if !database.IsTokenValid(maybeToken) {
2017-06-13 00:39:12 +02:00
logEntry.Warn("receive wrong token")
2017-06-12 22:32:27 +02:00
break
} else {
token = maybeToken
2017-06-13 00:39:12 +02:00
logEntry.Info("receive valid token")
2017-06-12 22:32:27 +02:00
}
continue
}
var entry log.Entry
msgType, msg, err := c.ReadMessage()
if msgType == -1 {
c.Close()
logEntry.Info("connecting closed")
break
}
if err != nil {
2017-06-13 00:39:12 +02:00
logEntry.Error("receiving log entry:", err)
2017-06-12 22:32:27 +02:00
break
}
err = json.Unmarshal(msg, &entry)
if err != nil {
logEntry.Error("umarshal log entry:", err)
break
}
2017-06-16 10:33:35 +02:00
dbEntry := database.InsertEntry(token, &entry)
if dbEntry != nil && h.Notify != nil {
h.Notify.Send(dbEntry)
2017-06-24 13:17:47 +02:00
} else {
l := logOutput.NewLogger()
e := log.New()
e.Text = "No notifier found"
e.Level = log.WarnLevel
l.Hook(e)
2017-06-16 10:33:35 +02:00
}
2017-06-12 22:32:27 +02:00
}
}