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()
34 case new_message, ok := <-store.Add:
38 messages.PushBack(new_message)
39 for waiter := waiting.Front(); waiter != nil; waiter = waiter.Next() {
40 waiter.Value.(*StoreRequest).Messages <- []Message{*new_message}
41 close(waiter.Value.(*StoreRequest).Messages)
44 if message_count < max_messages {
47 messages.Remove(messages.Front())
49 case request, ok := <-store.Get:
53 if messages.Back() == nil || !request.StartTime.Before(messages.Back().Value.(*Message).Time) {
54 waiting.PushBack(request)
56 start := messages.Back()
58 if messages.Front().Value.(*Message).Time.After(request.StartTime) {
59 start = messages.Front()
60 response_size = message_count
62 for start.Prev().Value.(*Message).Time.After(request.StartTime) {
67 response_messages := make([]Message, 0, response_size)
68 for m := start; m != nil; m = m.Next() {
69 response_messages = append(response_messages, *m.Value.(*Message))
71 request.Messages <- response_messages
77 func start_store() Store {
78 store := Store{make(chan *Message, 20), make(chan *StoreRequest, 20)}
79 go manage_store(store)
83 func start_server(store Store) {
84 http.HandleFunc("/fetch", func(w http.ResponseWriter, r *http.Request) {
86 url_since := r.FormValue("since")
88 err := json.Unmarshal([]byte(url_since), &since)
90 log.Print("fetch: parse since: ", err)
91 w.WriteHeader(http.StatusBadRequest)
92 w.Write([]byte("Could not parse since as date"))
96 messages_from_store := make(chan []Message, 1)
97 store.Get <- &StoreRequest{since, messages_from_store}
99 json_encoded, err := json.Marshal(<-messages_from_store)
101 log.Print("json encode: ", err)
102 w.WriteHeader(http.StatusInternalServerError)
105 w.Header().Add("Content-Type", "application/json")
106 w.Write(json_encoded)
109 http.HandleFunc("/speak", func(w http.ResponseWriter, r *http.Request) {
110 store.Add <- &Message{time.Now(), r.FormValue("text")}
113 log.Fatal(http.ListenAndServe(":8080", nil))
117 store := start_store()