Last active
August 29, 2015 14:07
-
-
Save cnaize/895f61b762a9f5ee074c to your computer and use it in GitHub Desktop.
Testing chat
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 ( | |
"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"}) | |
} | |
//============================================================================== |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
added error handling