Hux is a channel based secure WebSocket manager
Use go get to install Hux
go get github.com/ahmetcanozcan/huxHux provides both server-side and client-side libraries.
Firstly import hux
import (
// Other libraries
"github.com/ahmetcanozcan/hux"
)Then create a hub to manage rooms and sockets in main function.
hub := hux.NewHub()Now, add a http handler
http.HandleFunc("/ws/hux", func(w http.ResponseWriter, r *http.Request) {
// Instantiate a Socket
socket, _:= hub.InstantiateSocket(w, r)
for {
select {
//Listen a event
case msg := <-socket.GetEvent("Hello"):
fmt.Println("GOT:", msg)
}
}
})Start listening
http.ListenAndServe(":8080",nil)more event handler can be added using case
case msg := <-socket.GetEvent("Join"):
fmt.Println("Join:", msg)
hub.GetRoom(msg).Add(socket)
hub.GetRoom(msg).Emit("New", "NEW SOCKET CONNECTED.")You can send and receive json
firstly, define a struct for json data
type Person struct {
Name string `json:"name"`
}then, handle the event that receive a json
case msg := <- socket.GetEvent("json"):
var p Person
msg.ParseJSON(&p)
socket.Emit("Hello","Wellcome, "+ p.Name )``
On client-side, hux provides a library too. Firstly add this script block before your code
<script src="https://unpkg.com/hux-client@1.0.1/hux.minifiy.js"></script>Then, you can write your client-side code like this:
<script>
//Initialize hux
var hux = new Hux();
// When hux connection is established, open event will be invoked.
hux.on('open', () => {
console.log('Connection established');
// Listen hello events from server
hux.on("World", () => console.log("GOT MESSAGE"));
// Send Hello message to server
hux.emit("Hello", "Hi");
// JSONs can be sent too
hux.emit("json",{name:"Test-User"})
})
</script>Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
