Skip to content

Instantly share code, notes, and snippets.

@imjasonh
Created September 6, 2012 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imjasonh/3651269 to your computer and use it in GitHub Desktop.
Save imjasonh/3651269 to your computer and use it in GitHub Desktop.
Simple HTTP server that enqueues subscribers and sends published messages to the oldest subscriber (and enqueues messages in case there are no subscribers)
package main
import (
"io"
"log"
"net/http"
)
const (
buffSize = 100
)
var (
subs = make(chan string, buffSize)
msgs = make(chan io.Reader, buffSize)
)
// send sends a message to a subscriber
func send(s string, m io.Reader) {
log.Println("Sending data to", s)
http.Post(s, "application/json", m)
}
// pub sends a message to the oldest registered subscriber or enqueues the message to be sent later
func pub(m io.Reader) {
select {
case s := <-subs:
send(s, m)
default:
msgs <- m
}
}
// sub registers a new subscriber or sends the subscriber the oldest enqueued message
func sub(s string) {
select {
case m := <-msgs:
send(s, m)
default:
subs <- s
}
}
func main() {
http.HandleFunc("/pub", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, r.Method+" not supported", http.StatusNotFound)
}
pub(r.Body)
})
http.HandleFunc("/sub", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, r.Method+" not supported", http.StatusNotFound)
}
sub(r.RemoteAddr)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
@imjasonh
Copy link
Author

imjasonh commented Sep 6, 2012

Note that this isn't a conventional "pubsub" system since messages are not published to all subscribers, just the single oldest subscriber in the queue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment