ws/controller.go

64 lines
1.5 KiB
Go
Raw Normal View History

package websocket
import (
2021-05-14 14:47:02 +00:00
"git.xdrm.io/go/ws/internal/uri/parser"
)
2021-05-14 14:47:02 +00:00
// Client contains 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)
}
2021-05-14 14:47:02 +00:00
// ControllerFunc is a websocket controller callback function
type ControllerFunc func(*Client, <-chan Message, chan<- Message, chan<- Message)
2021-05-14 14:47:02 +00:00
// Controller is a websocket controller
type Controller struct {
URI *parser.Scheme // uri scheme
Fun ControllerFunc // controller function
}
2021-05-14 14:47:02 +00:00
// ControllerSet is set of controllers
type ControllerSet struct {
Def *Controller // default controller
2021-05-14 14:47:02 +00:00
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) {
2021-05-14 15:19:02 +00:00
// 1. Initialise argument list
2021-05-14 14:47:02 +00:00
arguments := [][]string{{uri}}
2021-05-14 15:19:02 +00:00
// 2. Try each controller
2021-05-14 14:47:02 +00:00
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
}
}
2021-05-14 15:19:02 +00:00
// 3. If no controller found -> set default controller
if s.Def != nil {
return s.Def, arguments
}
2021-05-14 15:19:02 +00:00
// 4. If default is NIL, return empty controller
return nil, arguments
}