Created
November 12, 2015 23:38
-
-
Save benjojo/6b6cc4b0dd6d917bfc27 to your computer and use it in GitHub Desktop.
Publish collectd stats over a websocket, with a grep option too for scripts, Could be used for any kind of publishing of data over websockets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"github.com/tuxychandru/pubsub" | |
"golang.org/x/net/websocket" | |
"io/ioutil" | |
"net/http" | |
"strings" | |
) | |
var PubSub *pubsub.PubSub | |
func main() { | |
PubSub = pubsub.New(20) | |
bindaddr := flag.String("bind", "127.0.0.1:1189", "http bind") | |
flag.Parse() | |
http.HandleFunc("/poststat", addStat) | |
http.Handle("/statstream", websocket.Handler(streamStats)) | |
err := http.ListenAndServe(*bindaddr, nil) | |
if err != nil { | |
panic("ListenAndServe: " + err.Error()) | |
} | |
} | |
func addStat(rw http.ResponseWriter, req *http.Request) { | |
data, err := ioutil.ReadAll(req.Body) | |
if err != nil { | |
return | |
} | |
lines := strings.Split(string(data), "\n") | |
for _, v := range lines { | |
PubSub.Pub(v, "data") | |
} | |
} | |
func streamStats(ws *websocket.Conn) { | |
defer ws.Close() | |
grep := ws.Request().URL.Query().Get("grep") | |
inbound := make(chan interface{}, 2) | |
PubSub.AddSub(inbound, "data") | |
defer PubSub.Unsub(inbound, "data") | |
for { | |
in := <-inbound | |
if grep != "" && !strings.Contains(in.(string), grep) { | |
continue | |
} | |
err := websocket.Message.Send(ws, in.(string)) | |
if err != nil { | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment