Created
May 18, 2015 22:20
-
-
Save mschewe/47b08668e6b81f3d4b4f to your computer and use it in GitHub Desktop.
Sample application of gorilla/websocket and labstack/echo
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
$(function(){ | |
connect = function() { | |
ws = new WebSocket("ws://" + window.location.host + "/ws"); | |
ws.onopen = function(e) { | |
console.log("onopen", arguments); | |
}; | |
ws.onclose = function(e) { | |
console.log("onclose", arguments); | |
}; | |
ws.onmessage = function(e) { | |
console.log("onmessage", arguments); | |
}; | |
} | |
connect(); | |
}); // end of document ready |
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 ( | |
"log" | |
"net/http" | |
"github.com/gorilla/websocket" | |
"github.com/labstack/echo" | |
mw "github.com/labstack/echo/middleware" | |
) | |
type Message struct { | |
Type string `json:"type"` | |
Data interface{} `json:"data"` | |
} | |
var upgrader = websocket.Upgrader{ | |
ReadBufferSize: 1024, | |
WriteBufferSize: 1024, | |
} | |
func WsHandler(res http.ResponseWriter, req *http.Request) { | |
conn, err := upgrader.Upgrade(res, req, nil) | |
if err != nil { | |
log.Println(err) | |
return | |
} | |
err = conn.WriteJSON(Message{Type: "welcome", Data: "Welcome to websockets"}) | |
if err != nil { | |
log.Println(err) | |
return | |
} | |
} | |
func main() { | |
e := echo.New() | |
e.Use(mw.Logger()) | |
e.Use(mw.Recover()) | |
e.Static("/js", "public/js") | |
e.Static("/css", "public/css") | |
e.Static("/font", "public/font") | |
e.Index("public/index.html") | |
e.Get("/ws", WsHandler) | |
e.Run(":3000") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment