ws/controller.go

64 lines
1.5 KiB
Go

package websocket
import (
"git.xdrm.io/go/websocket/internal/uri/parser"
)
// Represents available information about a client
type Client struct {
Protocol string // choosen protocol (Sec-WebSocket-Protocol)
Arguments [][]string // URI parameters, index 0 is full URI, then matching groups
Store interface{} // store (for client implementation-specific data)
}
// Represents a websocket controller callback function
type ControllerFunc func(*Client, <-chan Message, chan<- Message, chan<- Message)
// Represents a websocket controller
type Controller struct {
URI *parser.Scheme // uri scheme
Fun ControllerFunc // controller function
}
// Represents a controller set
type ControllerSet struct {
Def *Controller // default controller
Uri []*Controller // uri controllers
}
// Match finds a controller for a given URI
// also it returns the matching string patterns
func (s *ControllerSet) Match(uri string) (*Controller, [][]string) {
/* (1) Initialise argument list */
arguments := [][]string{[]string{uri}}
/* (2) Try each controller */
for _, c := range s.Uri {
/* 1. If matches */
if c.URI.Match(uri) {
/* Extract matches */
match := c.URI.GetAllMatch()
/* Add them to the 'arg' attribute */
arguments = append(arguments, match...)
/* Mark that we have a controller */
return c, arguments
}
}
/* (3) If no controller found -> set default controller */
if s.Def != nil {
return s.Def, arguments
}
/* (4) If default is NIL, return empty controller */
return nil, arguments
}