logmania/api/receive/main.go

78 lines
1.6 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"
"github.com/genofire/logmania/database"
"github.com/genofire/logmania/log"
"github.com/gorilla/websocket"
)
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-13 00:21:19 +02:00
// init new Handler
2017-06-12 22:32:27 +02:00
func NewHandler() *Handler {
return &Handler{
upgrader: websocket.Upgrader{},
}
}
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
}
database.InsertEntry(token, &entry)
}
}