Created
December 3, 2014 00:23
-
-
Save stuross/261b625b617587855a33 to your computer and use it in GitHub Desktop.
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 ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"github.com/googollee/go-socket.io" | |
) | |
func main() { | |
server, err := socketio.NewServer(nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
server.On("connection", func(so socketio.Socket) { | |
log.Println("on connection") | |
so.Join("chat") | |
so.On("chat message", func(msg string) { | |
log.Println("emit:", so.Emit("chat message", msg)) | |
so.BroadcastTo("chat", "chat message", msg) | |
}) | |
so.On("disconnection", func() { | |
log.Println("on disconnect") | |
}) | |
}) | |
server.On("error", func(so socketio.Socket, err error) { | |
log.Println("error:", err) | |
}) | |
notify := func(w http.ResponseWriter, r *http.Request) { | |
if r.Method == "POST" { | |
var message_type string = r.Header.Get("X-Amz-Sns-Message-Type") | |
if message_type == "SubscriptionConfirmation" { | |
decoder := json.NewDecoder(r.Body) | |
var t map[string]interface{} | |
err := decoder.Decode(&t) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(t) | |
var subscribe_url string = t["SubscribeURL"].(string) | |
http.Get(subscribe_url) | |
} else if message_type == "Notification" { | |
decoder := json.NewDecoder(r.Body) | |
var t map[string]interface{} | |
err := decoder.Decode(&t) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(t) | |
server.BroadcastTo("chat", "chat message", t["Message"].(string)) | |
} | |
} | |
} | |
http.Handle("/socket.io/", server) | |
http.HandleFunc("/notify/", notify) | |
http.Handle("/", http.FileServer(http.Dir("./templates"))) | |
log.Println("listening...") | |
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment