3 import "container/list"
11 var port = flag.Int("port", 21059, "Port to listen on")
18 type StoreRequest struct {
20 Messages chan<- []Message
25 Get chan *StoreRequest
28 // TODO: Monotonic clock
30 func manage_store(store Store) {
31 messages := list.New()
38 case new_message, ok := <-store.Add:
42 messages.PushBack(new_message)
43 for waiter := waiting.Front(); waiter != nil; waiter = waiter.Next() {
44 waiter.Value.(*StoreRequest).Messages <- []Message{*new_message}
45 close(waiter.Value.(*StoreRequest).Messages)
48 if message_count < max_messages {
51 messages.Remove(messages.Front())
53 case request, ok := <-store.Get:
57 if messages.Back() == nil || !request.StartTime.Before(messages.Back().Value.(*Message).Time) {
58 waiting.PushBack(request)
60 start := messages.Back()
62 if messages.Front().Value.(*Message).Time.After(request.StartTime) {
63 start = messages.Front()
64 response_size = message_count
66 for start.Prev().Value.(*Message).Time.After(request.StartTime) {
71 response_messages := make([]Message, 0, response_size)
72 for m := start; m != nil; m = m.Next() {
73 response_messages = append(response_messages, *m.Value.(*Message))
75 request.Messages <- response_messages
81 func start_store() Store {
82 store := Store{make(chan *Message, 20), make(chan *StoreRequest, 20)}
83 go manage_store(store)
87 func start_server(store Store) {
88 http.HandleFunc("/fetch", func(w http.ResponseWriter, r *http.Request) {
90 url_since := r.FormValue("since")
92 err := json.Unmarshal([]byte(url_since), &since)
94 log.Print("fetch: parse since: ", err)
95 w.WriteHeader(http.StatusBadRequest)
96 w.Write([]byte("Could not parse since as date"))
100 messages_from_store := make(chan []Message, 1)
101 store.Get <- &StoreRequest{since, messages_from_store}
103 json_encoded, err := json.Marshal(<-messages_from_store)
105 log.Print("json encode: ", err)
106 w.WriteHeader(http.StatusInternalServerError)
109 w.Header().Add("Content-Type", "application/json")
110 w.Write(json_encoded)
113 http.HandleFunc("/speak", func(w http.ResponseWriter, r *http.Request) {
114 store.Add <- &Message{time.Now(), r.FormValue("text")}
117 log.Fatal(http.ListenAndServe(":" + strconv.Itoa(*port), nil))
121 store := start_store()