Skip to content

Instantly share code, notes, and snippets.

@skanehira
Last active February 8, 2021 13:53
Show Gist options
  • Save skanehira/1a82e8a4a9fc7aee51f3a18e77d4eac9 to your computer and use it in GitHub Desktop.
Save skanehira/1a82e8a4a9fc7aee51f3a18e77d4eac9 to your computer and use it in GitHub Desktop.
new WebSocket("ws://localhost:1323/ws", ["hello", "world"])
package main
import (
"fmt"
"github.com/labstack/echo/v4"
"golang.org/x/net/websocket"
)
func hello(c echo.Context) error {
websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close()
for {
// Write
err := websocket.Message.Send(ws, "Hello, Client!")
if err != nil {
c.Logger().Error(err)
}
// Read
msg := ""
err = websocket.Message.Receive(ws, &msg)
if err != nil {
c.Logger().Error(err)
}
fmt.Printf("%s\n", msg)
}
}).ServeHTTP(c.Response(), c.Request())
return nil
}
func auth(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
id := c.Request().Header["id"]
fmt.Println(id)
c.Set("id", id)
return next(c)
}
}
func wsParse(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
swp := c.Request().Header["Sec-Websocket-Protocol"]
c.Request().Header["id"] = swp
return auth(next)(c)
}
}
func main() {
e := echo.New()
e.Use(wsParse)
e.GET("/ws", hello)
e.Logger.Fatal(e.Start(":1323"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment