wserver

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2020 License: MIT Imports: 11 Imported by: 0

README

wserver

Build Status GoDoc Go Report Card

Package for setup websocket server with message push

This package is still not stable and not recommended to be used in production.

Basic Usage

Try to start a wserver, you just need to write like this.

Start wserver
server := wserver.NewServer(":12345")
if err := server.ListenAndServe(); err != nil {
    panic(err)
}

Now wserver listens on port: 12345.

Browser connecting

Now browser can connect to ws://ip:12345/ws. After connection established, browser should send a message to register. Register message looks like this.

{
    "token": "03A3408D-3BD4-4C6C-BDC7-8596E6D31848",
    "event": "whatever-it-interested"
}

The token is used for identification and event means what kind of messages the client interested (Like topic in MQ).

Push messages

Now you can send a request to http:/ip:12345/push to push a message. Message should look like this.

{
    "userId": "03A3408D-3BD4-4C6C-BDC7-8596E6D31848",
    "event": "whatever-it-interested",
    "message": "Hello World"
}

The userId is equal to token is not specified (customize by using server.AuthToken). The event is equal to that above and message is the real content will be sent to each websocket connection.

Example

The server code:

func main() {
	server := wserver.NewServer(":12345")

	// Define websocket connect url, default "/ws"
	server.WSPath = "/ws"
	// Define push message url, default "/push"
	server.PushPath = "/push"

	// Set AuthToken func to authorize websocket connection, token is sent by
	// client for registe.
	server.AuthToken = func(token string) (userID string, ok bool) {
		// TODO: check if token is valid and calculate userID
		if token == "aaa" {
			return "jack", true
		}

		return "", false
	}

	// Set PushAuth func to check push request. If the request is valid, returns
	// true. Otherwise return false and request will be ignored.
	server.PushAuth = func(r *http.Request) bool {
		// TODO: check if request is valid

		return true
	}

	// Run server
	if err := server.ListenAndServe(); err != nil {
		panic(err)
	}
}

If you want to run a demo. Then follow the steps below:

  • Go to _examples/server and run go run main.go to start a wserver.
  • Open the webpage _examples/index.html in the browser.
  • Go to _examples/push and run go run main.go to send some messages.

If all success, you will see the content like this:

demo-success

PS

Package is still not stable and I will improve it then.

PRs will be welcomed. 🍺

Documentation

Overview

Package wserver provides building simple websocket server with message push.

Index

Constants

This section is empty.

Variables

View Source
var ErrRequestIllegal = errors.New("request data illegal")

ErrRequestIllegal describes error when data of the request is unaccepted.

Functions

This section is empty.

Types

type BodyMessage added in v1.1.0

type BodyMessage struct {
	SystemType int `json:"SystemType,string,omitempty"`
}

BodyMessage defines messge body struct sent by client

type Conn

type Conn struct {
	Conn *websocket.Conn

	AfterReadFunc   func(messageType int, r io.Reader)
	BeforeCloseFunc func()
	// contains filtered or unexported fields
}

Conn wraps websocket.Conn with Conn. It defines to listen and read data from Conn.

func NewConn

func NewConn(conn *websocket.Conn) *Conn

NewConn wraps conn.

func (*Conn) Close added in v1.1.0

func (c *Conn) Close() error

Close close the connection.

func (*Conn) GetID

func (c *Conn) GetID() string

GetID returns the id generated using UUID algorithm.

func (*Conn) Listen

func (c *Conn) Listen()

Listen listens for receive data from websocket connection. It blocks until websocket connection is closed.

func (*Conn) Write

func (c *Conn) Write(p []byte) (n int, err error)

Write write p to the websocket connection. The error returned will always be nil if success.

type PushMessage added in v1.1.0

type PushMessage struct {
	UserID  string `json:"userId"`
	Event   string
	Message string
}

PushMessage defines message struct send by client to push to each connected websocket client.

type ReceiveMessage added in v1.1.0

type ReceiveMessage struct {
	Token string
	Event string
	Body  map[string]string
}

ReceiveMessage defines message struct client send after connect to the server.

type Server

type Server struct {
	// Address for server to listen on
	Addr string

	// Path for websocket request, default "/ws".
	WSPath string

	// Path for push message, default "/push".
	PushPath string

	StatusPath string

	LoopInterval int

	// Upgrader is for upgrade connection to websocket connection using
	// "github.com/gorilla/websocket".
	//
	// If Upgrader is nil, default upgrader will be used. Default upgrader is
	// set ReadBufferSize and WriteBufferSize to 1024, and CheckOrigin always
	// returns true.
	Upgrader *websocket.Upgrader

	// Check token if it's valid and return userID. If token is valid, userID
	// must be returned and ok should be true. Otherwise ok should be false.
	AuthToken func(token string) (userID string, ok bool)

	// Authorize push request. Message will be sent if it returns true,
	// otherwise the request will be discarded. Default nil and push request
	// will always be accepted.
	PushAuth func(r *http.Request) bool

	StatusAuth func(r *http.Request) bool

	PushMethod func(params map[string]string) ([]byte, error)
	// contains filtered or unexported fields
}

Server defines parameters for running websocket server.

func NewServer

func NewServer(addr string) *Server

NewServer creates a new Server.

func (*Server) Drop added in v1.1.0

func (s *Server) Drop(userID, event string) (int, error)

Drop find connections by userID and event, then close them. The userID can't be empty. The event is ignored if it's empty.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe listens on the TCP network address and handle websocket request.

func (*Server) Push

func (s *Server) Push(userID, event, message string) (int, error)

Push filters connections by userID and event, then write message

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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