Created
May 24, 2016 08:36
-
-
Save athoune/bc2fcc3302f8b7812b182f16a2e2b7ab to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"math/rand" | |
"net/http" | |
"sync" | |
"golang.org/x/net/websocket" | |
) | |
type Deployd struct { | |
pubsub map[int64]chan []byte | |
lock sync.Mutex | |
} | |
func (d *Deployd) bye(id int64) { | |
defer d.lock.Unlock() | |
d.lock.Lock() | |
delete(d.pubsub, id) | |
} | |
// Echo the data received on the WebSocket. | |
func (d *Deployd) Sub(ws *websocket.Conn) { | |
k := rand.Int63() | |
c := make(chan []byte) | |
d.pubsub[k] = c | |
defer d.bye(k) | |
for { | |
ws.Write(<-c) | |
} | |
} | |
func (d *Deployd) pub(msg []byte) { | |
defer d.lock.Unlock() | |
d.lock.Lock() | |
for _, c := range d.pubsub { | |
c <- msg | |
} | |
} | |
func (d *Deployd) Pub(w http.ResponseWriter, req *http.Request) { | |
msg := req.FormValue("msg") | |
d.pub([]byte(msg)) | |
w.WriteHeader(201) | |
} | |
// This example demonstrates a trivial echo server. | |
func main() { | |
d := Deployd{} | |
d.pubsub = make(map[int64]chan []byte) | |
http.HandleFunc("/pub", d.Pub) | |
http.Handle("/sub", websocket.Handler(d.Sub)) | |
http.Handle("/", http.FileServer(http.Dir("static"))) | |
//http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { | |
//http.ServeFile(w, req, "static/index.html") | |
//}) | |
err := http.ListenAndServe(":12345", nil) | |
if err != nil { | |
panic("ListenAndServe: " + err.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment