-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.go
64 lines (53 loc) · 1.53 KB
/
commands.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright 2023 Kirill Scherba <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Commands module of Webrts server package
package teowebrtc_server
import (
"errors"
"strings"
"sync"
)
// Commands hold WebRTC server commands
type Commands struct {
m commandsMap
*sync.RWMutex
}
type commandsMap map[string]CommandFunc
type CommandFunc func(dc DataChannel, gw WebRTCData) (data []byte, err error)
// Init Commands receiver
func (c *Commands) init() {
c.m = make(commandsMap)
c.RWMutex = new(sync.RWMutex)
}
// Add new command
func (c *Commands) Add(command string, f CommandFunc) *Commands {
c.Lock()
defer c.Unlock()
c.m[command] = f
return c
}
// Execute command and return true if command find
func (c *Commands) exec(dc DataChannel, gw WebRTCData) (data []byte, err error, ok bool) {
c.RLock()
defer c.RUnlock()
// Split command to command and parameters and get command
p, _ := c.Params(gw, 0)
command := p[0]
// Execut command
f, ok := c.m[command]
if ok {
data, err = f(dc, gw)
}
return
}
// Params split command into parameters array. The first element of this array
// is command, next elements are parameters. The 'number' input argument is
// number of expected parameters without command.
func (c *Commands) Params(gw WebRTCData, number int) (params []string, err error) {
params = strings.Split(gw.GetCommand(), "/")
if len(params) < number+1 {
err = errors.New("wrong number of commands parameters")
}
return
}