Skip to content

Instantly share code, notes, and snippets.

@cnaize
Last active August 29, 2015 14:07
Show Gist options
  • Save cnaize/895f61b762a9f5ee074c to your computer and use it in GitHub Desktop.
Save cnaize/895f61b762a9f5ee074c to your computer and use it in GitHub Desktop.
Testing chat
package main
import (
"fmt"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
"net/http"
)
//==============================================================================
type Response map[string]interface{}
//==============================================================================
type Chat struct {
Msgs chan string
}
//==============================================================================
var (
Ct *Chat
)
//==============================================================================
func main() {
Ct = &Chat{Msgs: make(chan string, 1)}
m := martini.Classic()
m.Use(render.Renderer())
m.Get("/send/:msg", send)
m.Get("/watch", watch)
m.Run()
}
//==============================================================================
func send(param martini.Params, r render.Render) {
Ct.Msgs <- param["msg"]
fmt.Printf("Sent: %v", param["msg"])
r.JSON(http.StatusOK, Response{"status": "ok"})
}
//==============================================================================
func watch(rw http.ResponseWriter, r render.Render) {
var msg string
ok := true
for ok {
select {
case msg, ok = <-Ct.Msgs:
if i, err := rw.Write([]byte(msg)); err != nil {
r.JSON(http.StatusOK, Response{"status": "error", "descr": err.Error()})
return
} else {
fmt.Printf("i: %v", i)
}
fmt.Printf("Wrote: %v", msg)
f, ok := rw.(http.Flusher)
if ok {
f.Flush()
fmt.Println("Flushed")
} else {
r.JSON(http.StatusOK, Response{"status": "error", "descr": "CANT_FLUSH"})
return
}
}
}
r.JSON(http.StatusOK, Response{"status": "ok", "descr": "finished"})
}
//==============================================================================
@cnaize
Copy link
Author

cnaize commented Oct 13, 2014

added error handling

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