hux

package module
v0.0.0-...-69e87f5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2020 License: MIT Imports: 8 Imported by: 0

README

CircleCI GitHub go.mod Go version Codacy grade

Hux is a channel based secure WebSocket manager

Installation

Use go get to install Hux

go get  github.com/ahmetcanozcan/hux

Usage

Hux 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>

Contributing

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.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Configs = struct {
	DefaultRoomName string
}{
	DefaultRoomName: "main",
}

Configs : configurations for `Hux`

View Source
var ErrRead error = errors.New("socket : read error ")

ErrRead : when a socket reads error except connection close

View Source
var ErrSocketConnection error = errors.New("connection : socket connection error")

ErrSocketConnection : Socket connection error

Functions

This section is empty.

Types

type Event

type Event chan Message

Event :

type Hub

type Hub struct {
	Upgrader    websocket.Upgrader
	DefaultRoom *Room
	// contains filtered or unexported fields
}

Hub :

func NewHub

func NewHub() *Hub

NewHub :

func (*Hub) Emit

func (h *Hub) Emit(name string, data interface{})

Emit :

func (*Hub) GetRoom

func (h *Hub) GetRoom(name string) *Room

GetRoom : Returns a existing room. if it's not exist, creates and returns a new room

func (*Hub) InstantiateSocket

func (h *Hub) InstantiateSocket(w http.ResponseWriter, r *http.Request) (*Socket, error)

InstantiateSocket :

type Message

type Message string

Message :

func (Message) ParseJSON

func (m Message) ParseJSON(v interface{}) error

ParseJSON :

func (Message) String

func (m Message) String() string

type Room

type Room struct {
	// contains filtered or unexported fields
}

Room : a Room is a socket group

func NewRoom

func NewRoom() *Room

NewRoom : Instantiate a new room

func (*Room) Add

func (r *Room) Add(s *Socket)

Add : add a socket to the room

func (*Room) Emit

func (r *Room) Emit(name string, data interface{})

Emit : emit message to all sockets in the room

func (*Room) Remove

func (r *Room) Remove(s *Socket)

Remove : remove a socket from the room

type Socket

type Socket struct {
	// contains filtered or unexported fields
}

Socket : Socket is a websocket conection handler

func (*Socket) Broadcast

func (s *Socket) Broadcast(name string, data interface{})

Broadcast : Send message all clients except its client

func (*Socket) Disconnect

func (s *Socket) Disconnect()

Disconnect : Close connection

func (*Socket) Emit

func (s *Socket) Emit(name string, data interface{})

Emit : Send a message to client.

func (*Socket) GetEvent

func (s *Socket) GetEvent(name string) Event

GetEvent : Returns an event by given name. if event is not defined then defines and returns it

func (*Socket) Join

func (s *Socket) Join(r *Room)

Join : adds itself to the given room

func (*Socket) LeaveRoom

func (s *Socket) LeaveRoom()

LeaveRoom : leaves its room

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL