3 import "container/list"
14 type StoreRequest struct {
16 Messages chan<- []Message
21 Get chan *StoreRequest
24 // TODO: Monotonic clock
26 func manage_store(store Store) {
27 messages := list.New()
33 case new_message := <-store.Add:
34 messages.PushBack(new_message)
35 for waiter := waiting.Front(); waiter != nil; waiter = waiter.Next() {
36 waiter.Value.(*StoreRequest).Messages <- []Message{*new_message}
37 close(waiter.Value.(*StoreRequest).Messages)
40 if message_count < max_messages {
43 messages.Remove(messages.Front())
45 case request := <-store.Get:
46 if messages.Back() == nil || !request.StartTime.Before(messages.Back().Value.(*Message).Time) {
47 waiting.PushBack(request)
49 start := messages.Back()
51 if messages.Front().Value.(*Message).Time.After(request.StartTime) {
52 start = messages.Front()
53 response_size = message_count
55 for start.Prev().Value.(*Message).Time.After(request.StartTime) {
60 response_messages := make([]Message, 0, response_size)
61 for m := start; m != nil; m = m.Next() {
62 response_messages = append(response_messages, *m.Value.(*Message))
64 request.Messages <- response_messages
70 func start_store() Store {
71 store := Store{make(chan *Message, 20), make(chan *StoreRequest, 20)}
72 go manage_store(store)
76 func start_server(store Store) {
77 http.HandleFunc("/fetch", func(w http.ResponseWriter, r *http.Request) {
79 url_since := r.FormValue("since")
81 err := json.Unmarshal([]byte(url_since), &since)
83 log.Print("fetch: parse since: ", err)
84 w.WriteHeader(http.StatusBadRequest)
85 w.Write([]byte("Could not parse since as date"))
89 messages_from_store := make(chan []Message, 1)
90 store.Get <- &StoreRequest{since, messages_from_store}
92 json_encoded, err := json.Marshal(<-messages_from_store)
94 log.Print("json encode: ", err)
95 w.WriteHeader(http.StatusInternalServerError)
98 w.Header().Add("Content-Type", "application/json")
102 http.HandleFunc("/speak", func(w http.ResponseWriter, r *http.Request) {
103 store.Add <- &Message{time.Now(), r.FormValue("text")}
106 log.Fatal(http.ListenAndServe(":8080", nil))
110 store := start_store()