forked from thecubed/gogstash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
outputsocket.go
68 lines (58 loc) · 1.57 KB
/
outputsocket.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
65
66
67
68
package socket
import (
"context"
"net"
"github.com/tsaikd/gogstash/config"
"github.com/tsaikd/gogstash/config/logevent"
)
// ModuleName is the name used in config file
const ModuleName = "socket"
// OutputConfig holds the configuration json fields and internal objects
type OutputConfig struct {
config.OutputConfig
Socket string `json:"socket"` // Type of socket, must be one of ["tcp", "unix", "unixpacket"].
Address string `json:"address"` // For TCP, address must have the form `host:port`. For Unix networks, the address must be a file system path.
outputSocket *net.Conn
}
// DefaultOutputConfig returns an OutputConfig struct with default values
func DefaultOutputConfig() OutputConfig {
return OutputConfig{
OutputConfig: config.OutputConfig{
CommonConfig: config.CommonConfig{
Type: ModuleName,
},
},
}
}
// InitHandler initialize the output plugin
func InitHandler(ctx context.Context, raw *config.ConfigRaw) (config.TypeOutputConfig, error) {
conf := DefaultOutputConfig()
if err := config.ReflectConfig(raw, &conf); err != nil {
return nil, err
}
// init Socket
conn, err := net.Dial(conf.Socket, conf.Address)
if err != nil {
return nil, err
}
go func() {
select {
case <-ctx.Done():
conn.Close()
}
}()
conf.outputSocket = &conn
return &conf, nil
}
// Output event
func (t *OutputConfig) Output(ctx context.Context, event logevent.LogEvent) error {
b, err := event.MarshalJSON()
if err != nil {
return err
}
b = append(b, '\n')
if _, err := (*t.outputSocket).Write(b); err != nil {
return err
}
return nil
}