2018-08-23 00:34:02 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2018-08-23 01:21:53 +02:00
|
|
|
"git.lattuga.net/boyska/circolog"
|
2018-08-23 00:34:02 +02:00
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"gopkg.in/mcuadros/go-syslog.v2/format"
|
|
|
|
)
|
|
|
|
|
2018-08-23 12:25:07 +02:00
|
|
|
func setupHTTP(hub circolog.Hub) {
|
2018-08-23 00:56:27 +02:00
|
|
|
http.HandleFunc("/", getHTTPHandler(hub))
|
2018-08-23 00:34:02 +02:00
|
|
|
http.HandleFunc("/ws", getWSHandler(hub))
|
|
|
|
}
|
|
|
|
|
2018-08-23 01:21:53 +02:00
|
|
|
func getHTTPHandler(hub circolog.Hub) http.HandlerFunc {
|
2018-08-23 00:34:02 +02:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2018-08-23 01:21:53 +02:00
|
|
|
client := circolog.Client{
|
2018-08-23 02:05:50 +02:00
|
|
|
Messages: make(chan format.LogParts, 20),
|
2018-08-23 00:56:27 +02:00
|
|
|
Nofollow: true}
|
|
|
|
hub.Register <- client
|
|
|
|
|
|
|
|
for x := range client.Messages {
|
2018-08-23 15:35:55 +02:00
|
|
|
w.Write([]byte(circolog.FormatSyslog(x)))
|
2018-08-23 00:34:02 +02:00
|
|
|
w.Write([]byte("\n"))
|
2018-08-23 00:56:27 +02:00
|
|
|
}
|
2018-08-23 00:34:02 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-23 01:21:53 +02:00
|
|
|
func getWSHandler(hub circolog.Hub) http.HandlerFunc {
|
2018-08-23 00:34:02 +02:00
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
ReadBufferSize: 1024,
|
|
|
|
WriteBufferSize: 1024,
|
|
|
|
}
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
conn, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2018-08-23 02:05:50 +02:00
|
|
|
client := circolog.Client{Messages: make(chan format.LogParts, 20)}
|
2018-08-23 00:34:02 +02:00
|
|
|
hub.Register <- client
|
|
|
|
|
|
|
|
// Allow collection of memory referenced by the caller by doing all work in
|
|
|
|
// new goroutines.
|
2018-08-23 01:21:53 +02:00
|
|
|
go func(conn *websocket.Conn, c circolog.Client) {
|
2018-08-23 00:34:02 +02:00
|
|
|
defer func() {
|
|
|
|
hub.Unregister <- c
|
|
|
|
conn.Close()
|
|
|
|
}()
|
|
|
|
for {
|
|
|
|
select {
|
2018-08-23 00:56:27 +02:00
|
|
|
case message, ok := <-c.Messages:
|
2018-08-23 00:34:02 +02:00
|
|
|
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
|
|
|
if !ok {
|
|
|
|
// The hub closed the channel.
|
|
|
|
conn.WriteMessage(websocket.CloseMessage, []byte{})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w, err := conn.NextWriter(websocket.TextMessage)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2018-08-23 15:35:55 +02:00
|
|
|
w.Write([]byte(circolog.FormatSyslog(message)))
|
2018-08-23 00:34:02 +02:00
|
|
|
|
|
|
|
if err := w.Close(); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// TODO: ticker/ping
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}(conn, client)
|
|
|
|
}
|
|
|
|
}
|