Skip to content

Instantly share code, notes, and snippets.

@aburd
Last active July 5, 2018 04:46
Show Gist options
  • Save aburd/0151f79a5e0809009ff740c269f7f81f to your computer and use it in GitHub Desktop.
Save aburd/0151f79a5e0809009ff740c269f7f81f to your computer and use it in GitHub Desktop.
A simple example of using Websockets in Go with the Gorilla lib
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/index.html")
})
http.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {
var conn, _ = upgrader.Upgrade(w, r, nil)
go func(conn *websocket.Conn) {
for {
_, msg, _ := conn.ReadMessage()
println(string(msg))
res := mStruct{
Name: "Aaron",
Message: fmt.Sprintf("%s back to you!", string(msg)),
}
println(string(res.Message))
conn.WriteJSON(res)
}
}(conn)
})
http.ListenAndServe(":3000", nil)
}
type mStruct struct {
Name string `json:"name"`
Message string `json:"message"`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment