1
0
Fork 0
burlesque/server.go

105 lines
2.1 KiB
Go
Raw Normal View History

2014-07-10 12:19:39 +00:00
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"runtime"
"strings"
)
func StatusHandler(w http.ResponseWriter, r *http.Request) {
info := make(map[string]map[string]uint)
for _, q := range queues {
info[q.Name] = map[string]uint{
"messages": q.Counter.Distance(),
"subscriptions": 0,
}
}
2014-07-16 18:57:54 +00:00
for _, r := range pool.Requests {
2014-07-10 12:19:39 +00:00
for _, q := range r.Queues {
info[q]["subscriptions"]++
}
}
2014-07-16 19:18:54 +00:00
jsn, _ := json.Marshal(info)
w.Write(jsn)
2014-07-10 12:19:39 +00:00
}
func DebugHandler(w http.ResponseWriter, r *http.Request) {
info := make(map[string]interface{})
2014-07-29 06:31:42 +00:00
info["version"] = Version
2014-07-10 12:19:39 +00:00
info["goroutines"] = runtime.NumGoroutine()
s, err := storage.Status()
if err != nil {
Error(err, "Failed to get Kyoto Cabinet status")
}
info["kyoto_cabinet"] = s
2014-07-16 19:18:54 +00:00
jsn, _ := json.Marshal(info)
w.Write(jsn)
2014-07-10 12:19:39 +00:00
}
func PublishHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
msg, _ := ioutil.ReadAll(r.Body)
if len(msg) == 0 {
msg = Message(r.FormValue("msg"))
}
2014-07-17 13:22:37 +00:00
qname := r.FormValue("queue")
ok := RegisterPublication(qname, msg)
2014-07-16 17:47:08 +00:00
if ok {
2014-07-17 13:22:37 +00:00
Debug("Published message of %d bytes to queue %s", len(msg), qname)
2014-07-16 17:47:08 +00:00
w.Write([]byte("OK"))
} else {
2014-07-17 13:22:37 +00:00
Debug("Failed to publish message of %d bytes to queue %s", len(msg), qname)
2014-07-16 17:47:08 +00:00
http.Error(w, "FAIL", 500)
}
2014-07-10 12:19:39 +00:00
}
func SubscriptionHandler(w http.ResponseWriter, r *http.Request) {
2014-07-17 13:22:37 +00:00
rch := make(chan Response)
2014-07-16 17:50:05 +00:00
abort := make(chan bool, 1)
2014-07-10 12:19:39 +00:00
req := &Request{
2014-07-17 13:22:37 +00:00
Queues: strings.Split(r.FormValue("queues"), ","),
ResponseCh: rch,
Abort: abort,
2014-07-10 12:19:39 +00:00
}
2014-07-16 18:57:54 +00:00
go RegisterSubscription(req)
2014-07-10 12:19:39 +00:00
disconnected := w.(http.CloseNotifier).CloseNotify()
finished := make(chan bool)
go func() {
select {
case <-disconnected:
2014-07-17 13:22:37 +00:00
close(rch)
2014-07-16 17:50:05 +00:00
abort <- true
2014-07-10 12:19:39 +00:00
case <-finished:
}
2014-07-17 13:22:37 +00:00
req.Purge()
2014-07-10 12:19:39 +00:00
}()
2014-07-17 13:22:37 +00:00
res, ok := <-rch
if !ok {
2014-07-10 12:19:39 +00:00
return
}
w.Header().Set("Queue", res.Queue)
w.Write(res.Message)
2014-07-15 03:42:06 +00:00
Debug("Recieved message of %d bytes from queue %s", len(res.Message), res.Queue)
2014-07-10 12:19:39 +00:00
finished <- true
}
func SetupServer() {
http.HandleFunc("/status", StatusHandler)
http.HandleFunc("/debug", DebugHandler)
http.HandleFunc("/publish", PublishHandler)
http.HandleFunc("/subscribe", SubscriptionHandler)
}