Last active
July 5, 2018 04:46
-
-
Save aburd/0151f79a5e0809009ff740c269f7f81f to your computer and use it in GitHub Desktop.
A simple example of using Websockets in Go with the Gorilla lib
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 ( | |
"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