Created
September 6, 2012 04:34
-
-
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)
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 ( | |
"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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.