本文整理匯總了Golang中github.com/mozilla-services/heka/message.Message.GetPayload方法的典型用法代碼示例。如果您正苦於以下問題:Golang Message.GetPayload方法的具體用法?Golang Message.GetPayload怎麽用?Golang Message.GetPayload使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/mozilla-services/heka/message.Message
的用法示例。
在下文中一共展示了Message.GetPayload方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Run
func (self *LogOutput) Run(or OutputRunner, h PluginHelper) (err error) {
inChan := or.InChan()
var (
pack *PipelinePack
msg *message.Message
)
for plc := range inChan {
pack = plc.Pack
msg = pack.Message
if self.payloadOnly {
log.Printf(msg.GetPayload())
} else {
log.Printf("<\n\tTimestamp: %s\n"+
"\tType: %s\n"+
"\tHostname: %s\n"+
"\tPid: %d\n"+
"\tUUID: %s\n"+
"\tLogger: %s\n"+
"\tPayload: %s\n"+
"\tEnvVersion: %s\n"+
"\tSeverity: %d\n"+
"\tFields: %+v\n"+
"\tCaptures: %v\n>\n",
time.Unix(0, msg.GetTimestamp()), msg.GetType(),
msg.GetHostname(), msg.GetPid(), msg.GetUuidString(),
msg.GetLogger(), msg.GetPayload(), msg.GetEnvVersion(),
msg.GetSeverity(), msg.Fields, plc.Captures)
}
pack.Recycle()
}
return
}
示例2: WriteToBuffer
func (so *S3Output) WriteToBuffer(buffer *bytes.Buffer, msg *message.Message, or OutputRunner) (err error) {
_, err = buffer.Write([]byte(msg.GetPayload()))
if err != nil {
return
}
if buffer.Len() > so.config.BufferChunkLimit {
err = so.SaveToDisk(buffer, or)
}
return
}
示例3: Format
func (c *CleanMessageFormatter) Format(m *message.Message) (doc []byte, err error) {
buf := bytes.Buffer{}
buf.WriteString(`{`)
// Iterates over fields configured for clean formating
for _, f := range c.fields {
switch strings.ToLower(f) {
case "uuid":
writeField(&buf, f, strconv.Quote(m.GetUuidString()))
case "timestamp":
t := time.Unix(0, m.GetTimestamp()).UTC()
writeField(&buf, f, strconv.Quote(t.Format(c.timestampFormat)))
case "type":
writeField(&buf, f, strconv.Quote(m.GetType()))
case "logger":
writeField(&buf, f, strconv.Quote(m.GetLogger()))
case "severity":
writeField(&buf, f, strconv.Itoa(int(m.GetSeverity())))
case "payload":
if utf8.ValidString(m.GetPayload()) {
writeField(&buf, f, strconv.Quote(m.GetPayload()))
}
case "envversion":
writeField(&buf, f, strconv.Quote(m.GetEnvVersion()))
case "pid":
writeField(&buf, f, strconv.Itoa(int(m.GetPid())))
case "hostname":
writeField(&buf, f, strconv.Quote(m.GetHostname()))
case "fields":
for _, field := range m.Fields {
switch field.GetValueType() {
case message.Field_STRING:
writeField(&buf, *field.Name, strconv.Quote(field.GetValue().(string)))
case message.Field_BYTES:
data := field.GetValue().([]byte)[:]
writeField(&buf, *field.Name, strconv.Quote(base64.StdEncoding.EncodeToString(data)))
case message.Field_INTEGER:
writeField(&buf, *field.Name, strconv.FormatInt(field.GetValue().(int64), 10))
case message.Field_DOUBLE:
writeField(&buf, *field.Name, strconv.FormatFloat(field.GetValue().(float64),
'g', -1, 64))
case message.Field_BOOL:
writeField(&buf, *field.Name, strconv.FormatBool(field.GetValue().(bool)))
}
}
default:
// Search fo a given fields in the message
err = fmt.Errorf("Unable to find field: %s", f)
return
}
}
buf.WriteString(`}`)
doc = buf.Bytes()
return
}
示例4: Run
func (cwo *CloudwatchOutput) Run(or pipeline.OutputRunner, h pipeline.PluginHelper) (err error) {
inChan := or.InChan()
payloads := make(chan CloudwatchDatapoints, cwo.backlog)
go cwo.Submitter(payloads, or)
var (
pack *pipeline.PipelinePack
msg *message.Message
rawDataPoints *CloudwatchDatapointPayload
dataPoints *CloudwatchDatapoints
)
dataPoints = new(CloudwatchDatapoints)
dataPoints.Datapoints = make([]cloudwatch.MetricDatum, 0, 0)
for pack = range inChan {
rawDataPoints = new(CloudwatchDatapointPayload)
msg = pack.Message
err = json.Unmarshal([]byte(msg.GetPayload()), rawDataPoints)
if err != nil {
or.LogMessage(fmt.Sprintf("warning, unable to parse payload: %s", err))
err = nil
continue
}
// Run through the list and convert them to CloudwatchDatapoints
for _, rawDatum := range rawDataPoints.Datapoints {
datum := cloudwatch.MetricDatum{
Dimensions: rawDatum.Dimensions,
MetricName: rawDatum.MetricName,
Unit: rawDatum.Unit,
Value: rawDatum.Value,
StatisticValues: rawDatum.StatisticValues,
}
if rawDatum.Timestamp != "" {
parsedTime, err := message.ForgivingTimeParse("", rawDatum.Timestamp, cwo.tzLocation)
if err != nil {
or.LogMessage(fmt.Sprintf("unable to parse timestamp for datum: %s", rawDatum))
continue
}
datum.Timestamp = parsedTime
}
dataPoints.Datapoints = append(dataPoints.Datapoints, datum)
}
payloads <- *dataPoints
dataPoints.Datapoints = dataPoints.Datapoints[:0]
rawDataPoints.Datapoints = rawDataPoints.Datapoints[:0]
pack.Recycle()
}
or.LogMessage("shutting down AWS Cloudwatch submitter")
cwo.stopChan <- true
<-cwo.stopChan
return
}
示例5: Run
func (s *SmtpOutput) Run(or OutputRunner, h PluginHelper) (err error) {
inChan := or.InChan()
var (
pack *PipelinePack
msg *message.Message
contents []byte
subject string
message string
headerText string
)
if s.conf.Subject == "" {
subject = "Heka [" + or.Name() + "]"
} else {
subject = s.conf.Subject
}
header := make(map[string]string)
header["From"] = s.conf.SendFrom
header["Subject"] = subject
header["MIME-Version"] = "1.0"
header["Content-Type"] = "text/plain; charset=\"utf-8\""
header["Content-Transfer-Encoding"] = "base64"
for k, v := range header {
headerText += fmt.Sprintf("%s: %s\r\n", k, v)
}
for pack = range inChan {
msg = pack.Message
message = headerText
if s.conf.PayloadOnly {
message += "\r\n" + base64.StdEncoding.EncodeToString([]byte(msg.GetPayload()))
err = s.sendFunction(s.conf.Host, s.auth, s.conf.SendFrom, s.conf.SendTo, []byte(message))
} else {
if contents, err = json.Marshal(msg); err == nil {
message += "\r\n" + base64.StdEncoding.EncodeToString(contents)
err = s.sendFunction(s.conf.Host, s.auth, s.conf.SendFrom, s.conf.SendTo, []byte(message))
} else {
or.LogError(err)
}
}
if err != nil {
or.LogError(err)
}
pack.Recycle()
}
return
}
示例6: loadSandbox
// Parses a Heka message and extracts the information necessary to start a new
// SandboxFilter
func (this *SandboxManagerFilter) loadSandbox(fr pipeline.FilterRunner,
h pipeline.PluginHelper, dir string, msg *message.Message) (err error) {
fv, _ := msg.GetFieldValue("config")
if config, ok := fv.(string); ok {
var configFile pipeline.ConfigFile
if _, err = toml.Decode(config, &configFile); err != nil {
return fmt.Errorf("loadSandbox failed: %s\n", err)
} else {
for name, conf := range configFile {
name = getSandboxName(fr.Name(), name)
if _, ok := h.Filter(name); ok {
// todo support reload
return fmt.Errorf("loadSandbox failed: %s is already running", name)
}
fr.LogMessage(fmt.Sprintf("Loading: %s", name))
confFile := filepath.Join(dir, fmt.Sprintf("%s.toml", name))
err = ioutil.WriteFile(confFile, []byte(config), 0600)
if err != nil {
return
}
var sbc SandboxConfig
if err = toml.PrimitiveDecode(conf, &sbc); err != nil {
return fmt.Errorf("loadSandbox failed: %s\n", err)
}
scriptFile := filepath.Join(dir, fmt.Sprintf("%s.%s", name, sbc.ScriptType))
err = ioutil.WriteFile(scriptFile, []byte(msg.GetPayload()), 0600)
if err != nil {
removeAll(dir, fmt.Sprintf("%s.*", name))
return
}
// check/clear the old state preservation file
// this avoids issues with changes to the data model since the last load
// and prevents holes in the graph from looking like anomalies
os.Remove(filepath.Join(pipeline.PrependBaseDir(DATA_DIR), name+DATA_EXT))
var runner pipeline.FilterRunner
runner, err = this.createRunner(dir, name, conf)
if err != nil {
removeAll(dir, fmt.Sprintf("%s.*", name))
return
}
err = h.PipelineConfig().AddFilterRunner(runner)
if err == nil {
this.currentFilters++
}
break // only interested in the first item
}
}
}
return
}
示例7: loadSandbox
// Parses a Heka message and extracts the information necessary to start a new
// SandboxFilter
func (this *SandboxManagerFilter) loadSandbox(fr pipeline.FilterRunner,
h pipeline.PluginHelper, dir string, msg *message.Message) (err error) {
fv, _ := msg.GetFieldValue("config")
if config, ok := fv.(string); ok {
var configFile pipeline.ConfigFile
if _, err = toml.Decode(config, &configFile); err != nil {
return fmt.Errorf("loadSandbox failed: %s\n", err)
}
for name, conf := range configFile {
name = getSandboxName(fr.Name(), name)
if _, ok := h.Filter(name); ok {
// todo support reload
return fmt.Errorf("loadSandbox failed: %s is already running", name)
}
fr.LogMessage(fmt.Sprintf("Loading: %s", name))
confFile := filepath.Join(dir, fmt.Sprintf("%s.toml", name))
err = ioutil.WriteFile(confFile, []byte(config), 0600)
if err != nil {
return
}
var sbc SandboxConfig
// Default, will get overwritten if necessary
sbc.ScriptType = "lua"
if err = toml.PrimitiveDecode(conf, &sbc); err != nil {
return fmt.Errorf("loadSandbox failed: %s\n", err)
}
scriptFile := filepath.Join(dir, fmt.Sprintf("%s.%s", name, sbc.ScriptType))
err = ioutil.WriteFile(scriptFile, []byte(msg.GetPayload()), 0600)
if err != nil {
removeAll(dir, fmt.Sprintf("%s.*", name))
return
}
var runner pipeline.FilterRunner
runner, err = this.createRunner(dir, name, conf)
if err != nil {
removeAll(dir, fmt.Sprintf("%s.*", name))
return
}
err = this.pConfig.AddFilterRunner(runner)
if err == nil {
atomic.AddInt32(&this.currentFilters, 1)
}
break // only interested in the first item
}
}
return
}
示例8: Run
func (n *NagiosOutput) Run(or OutputRunner, h PluginHelper) (err error) {
inChan := or.InChan()
var (
pack *PipelinePack
msg *message.Message
payload string
)
for pack = range inChan {
msg = pack.Message
payload = msg.GetPayload()
pos := strings.IndexAny(payload, ":")
state := "3" // UNKNOWN
if pos != -1 {
switch payload[:pos] {
case "OK":
state = "0"
case "WARNING":
state = "1"
case "CRITICAL":
state = "2"
}
}
data := url.Values{
"cmd_typ": {"30"}, // PROCESS_SERVICE_CHECK_RESULT
"cmd_mod": {"2"}, // CMDMODE_COMMIT
"host": {msg.GetHostname()},
"service": {msg.GetLogger()},
"plugin_state": {state},
"plugin_output": {payload[pos+1:]},
"performance_data": {""}}
req, err := http.NewRequest("POST", n.conf.Url,
strings.NewReader(data.Encode()))
if err == nil {
req.SetBasicAuth(n.conf.Username, n.conf.Password)
if resp, err := n.client.Do(req); err == nil {
resp.Body.Close()
} else {
or.LogError(err)
}
} else {
or.LogError(err)
}
pack.Recycle()
}
return
}
示例9: loadSandbox
func (this *SandboxManagerFilter) loadSandbox(fr FilterRunner,
h PluginHelper, dir string, msg *message.Message) (err error) {
fv, _ := msg.GetFieldValue("config")
if config, ok := fv.(string); ok {
var configFile ConfigFile
if _, err = toml.Decode(config, &configFile); err != nil {
return fmt.Errorf("loadSandbox failed: %s\n", err)
} else {
for name, conf := range configFile {
name = getSandboxName(fr.Name(), name)
if _, ok := h.Filter(name); ok {
// todo support reload
return fmt.Errorf("loadSandbox failed: %s is already running", name)
}
fr.LogMessage(fmt.Sprintf("Loading: %s", name))
confFile := path.Join(dir, fmt.Sprintf("%s.toml", name))
err = ioutil.WriteFile(confFile, []byte(config), 0600)
if err != nil {
return
}
var sbfc SandboxFilterConfig
if err = toml.PrimitiveDecode(conf, &sbfc); err != nil {
return fmt.Errorf("loadSandbox failed: %s\n", err)
}
scriptFile := path.Join(dir, fmt.Sprintf("%s.%s", name, sbfc.Sbc.ScriptType))
err = ioutil.WriteFile(scriptFile, []byte(msg.GetPayload()), 0600)
if err != nil {
removeAll(dir, fmt.Sprintf("%s.*", name))
return
}
var runner FilterRunner
runner, err = createRunner(dir, name, conf)
if err != nil {
removeAll(dir, fmt.Sprintf("%s.*", name))
return
}
err = h.PipelineConfig().AddFilterRunner(runner)
if err == nil {
this.currentFilters++
}
break // only interested in the first item
}
}
}
return
}
示例10: Run
func (n *NagiosOutput) Run(or OutputRunner, h PluginHelper) (err error) {
inChan := or.InChan()
var (
pack *PipelinePack
msg *message.Message
payload string
)
for pack = range inChan {
msg = pack.Message
payload = msg.GetPayload()
pos := strings.IndexAny(payload, ":")
state := "3" // UNKNOWN
if pos != -1 {
switch payload[:pos] {
case "OK":
state = "0"
case "WARNING":
state = "1"
case "CRITICAL":
state = "2"
}
}
host := n.conf.NagiosHost
if host == "" {
host = msg.GetHostname()
}
service_description := n.conf.NagiosServiceDescription
if service_description == "" {
service_description = msg.GetLogger()
}
payload = payload[pos+1:]
err = n.submitter(host, service_description, state, payload)
if err != nil {
err = NewRetryMessageError(err.Error())
pack.Recycle(err)
continue
}
or.UpdateCursor(pack.QueueCursor)
pack.Recycle(nil)
}
return
}
示例11: getMessageVariable
func getMessageVariable(msg *message.Message, mvar *messageVariable) string {
if mvar.header {
switch mvar.name {
case "Type":
return msg.GetType()
case "Logger":
return msg.GetLogger()
case "Hostname":
return msg.GetHostname()
case "Payload":
return msg.GetPayload()
default:
return ""
}
} else {
return getFieldAsString(msg, mvar)
}
}
示例12: Run
func (self *DashboardOutput) Run(or OutputRunner, h PluginHelper) (err error) {
inChan := or.InChan()
ticker := or.Ticker()
var (
ok = true
plc *PipelineCapture
pack *PipelinePack
msg *message.Message
)
for ok {
select {
case plc, ok = <-inChan:
if !ok {
break
}
pack = plc.Pack
msg = pack.Message
switch msg.GetType() {
case "heka.all-report":
fn := path.Join(self.workingDirectory, "heka_report.json")
overwriteFile(fn, msg.GetPayload())
case "heka.sandbox-output":
tmp, ok := msg.GetFieldValue("payload_type")
if ok {
if pt, ok := tmp.(string); ok && pt == "cbuf" {
html := path.Join(self.workingDirectory, msg.GetLogger()+".html")
_, err := os.Stat(html)
if err != nil {
overwriteFile(html, fmt.Sprintf(getCbufTemplate(), msg.GetLogger(), msg.GetLogger()))
}
fn := path.Join(self.workingDirectory, msg.GetLogger()+"."+pt)
overwriteFile(fn, msg.GetPayload())
}
}
case "heka.sandbox-terminated":
fn := path.Join(self.workingDirectory, self.terminationFile)
if file, err := os.OpenFile(fn, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644); err == nil {
line := fmt.Sprintf("%d\t%s\t%v\n", msg.GetTimestamp()/1e9, msg.GetLogger(), msg.GetPayload())
file.WriteString(line)
file.Close()
}
}
plc.Pack.Recycle()
case <-ticker:
go h.PipelineConfig().allReportsMsg()
}
}
return
}
示例13: main
//.........這裏部分代碼省略.........
fmt.Printf("Match specification - %s\n", err)
os.Exit(2)
}
var file *os.File
if file, err = os.Open(flag.Arg(0)); err != nil {
fmt.Printf("%s\n", err)
os.Exit(3)
}
defer file.Close()
var out *os.File
if "" == *flagOutput {
out = os.Stdout
} else {
if out, err = os.OpenFile(*flagOutput, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
fmt.Printf("%s\n", err)
os.Exit(4)
}
defer out.Close()
}
var offset int64
if offset, err = file.Seek(*flagOffset, 0); err != nil {
fmt.Printf("%s\n", err)
os.Exit(5)
}
sRunner, err := makeSplitterRunner()
if err != nil {
fmt.Println(err)
os.Exit(7)
}
msg := new(message.Message)
var processed, matched int64
fmt.Printf("Input:%s Offset:%d Match:%s Format:%s Tail:%t Output:%s\n",
flag.Arg(0), *flagOffset, *flagMatch, *flagFormat, *flagTail, *flagOutput)
for true {
n, record, err := sRunner.GetRecordFromStream(file)
if n > 0 && n != len(record) {
fmt.Printf("Corruption detected at offset: %d bytes: %d\n", offset, n-len(record))
}
if err != nil {
if err == io.EOF {
if !*flagTail || "count" == *flagFormat {
break
}
time.Sleep(time.Duration(500) * time.Millisecond)
} else {
break
}
} else {
if len(record) > 0 {
processed += 1
headerLen := int(record[1]) + message.HEADER_FRAMING_SIZE
if err = proto.Unmarshal(record[headerLen:], msg); err != nil {
fmt.Printf("Error unmarshalling message at offset: %d error: %s\n", offset, err)
continue
}
if !match.Match(msg) {
continue
}
matched += 1
switch *flagFormat {
case "count":
// no op
case "json":
contents, _ := json.Marshal(msg)
fmt.Fprintf(out, "%s\n", contents)
case "heka":
fmt.Fprintf(out, "%s", record)
default:
fmt.Fprintf(out, "Timestamp: %s\n"+
"Type: %s\n"+
"Hostname: %s\n"+
"Pid: %d\n"+
"UUID: %s\n"+
"Logger: %s\n"+
"Payload: %s\n"+
"EnvVersion: %s\n"+
"Severity: %d\n"+
"Fields: %+v\n\n",
time.Unix(0, msg.GetTimestamp()), msg.GetType(),
msg.GetHostname(), msg.GetPid(), msg.GetUuidString(),
msg.GetLogger(), msg.GetPayload(), msg.GetEnvVersion(),
msg.GetSeverity(), msg.Fields)
}
}
}
offset += int64(n)
}
fmt.Printf("Processed: %d, matched: %d messages\n", processed, matched)
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(6)
}
}
示例14: EncoderSpec
func EncoderSpec(c gs.Context) {
t := new(ts.SimpleT)
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// NewPipelineConfig sets up Globals which is needed for the
// pipeline.Prepend*Dir functions to not die during plugin Init().
_ = pipeline.NewPipelineConfig(nil)
c.Specify("A SandboxEncoder", func() {
encoder := new(SandboxEncoder)
conf := encoder.ConfigStruct().(*SandboxEncoderConfig)
supply := make(chan *pipeline.PipelinePack, 1)
pack := pipeline.NewPipelinePack(supply)
pack.Message.SetPayload("original")
pack.Message.SetType("my_type")
pack.Message.SetPid(12345)
pack.Message.SetSeverity(4)
pack.Message.SetHostname("hostname")
pack.Message.SetTimestamp(54321)
pack.Message.SetUuid(uuid.NewRandom())
var (
result []byte
err error
)
c.Specify("emits JSON correctly", func() {
conf.ScriptFilename = "../lua/testsupport/encoder_json.lua"
err = encoder.Init(conf)
c.Expect(err, gs.IsNil)
result, err = encoder.Encode(pack)
c.Expect(err, gs.IsNil)
msg := new(message.Message)
err = json.Unmarshal(result, msg)
c.Expect(err, gs.IsNil)
c.Expect(msg.GetTimestamp(), gs.Equals, int64(54321))
c.Expect(msg.GetPid(), gs.Equals, int32(12345))
c.Expect(msg.GetSeverity(), gs.Equals, int32(4))
c.Expect(msg.GetHostname(), gs.Equals, "hostname")
c.Expect(msg.GetPayload(), gs.Equals, "original")
c.Expect(msg.GetType(), gs.Equals, "my_type")
})
c.Specify("emits text correctly", func() {
conf.ScriptFilename = "../lua/testsupport/encoder_text.lua"
err = encoder.Init(conf)
c.Expect(err, gs.IsNil)
result, err = encoder.Encode(pack)
c.Expect(err, gs.IsNil)
c.Expect(string(result), gs.Equals, "Prefixed original")
})
c.Specify("emits protobuf correctly", func() {
c.Specify("when inject_message is used", func() {
conf.ScriptFilename = "../lua/testsupport/encoder_protobuf.lua"
err = encoder.Init(conf)
c.Expect(err, gs.IsNil)
result, err = encoder.Encode(pack)
c.Expect(err, gs.IsNil)
msg := new(message.Message)
err = proto.Unmarshal(result, msg)
c.Expect(err, gs.IsNil)
c.Expect(msg.GetTimestamp(), gs.Equals, int64(54321))
c.Expect(msg.GetPid(), gs.Equals, int32(12345))
c.Expect(msg.GetSeverity(), gs.Equals, int32(4))
c.Expect(msg.GetHostname(), gs.Equals, "hostname")
c.Expect(msg.GetPayload(), gs.Equals, "mutated")
c.Expect(msg.GetType(), gs.Equals, "after")
})
c.Specify("when `write_message` is used", func() {
conf.ScriptFilename = "../lua/testsupport/encoder_writemessage.lua"
err = encoder.Init(conf)
c.Expect(err, gs.IsNil)
result, err = encoder.Encode(pack)
c.Expect(err, gs.IsNil)
msg := new(message.Message)
err = proto.Unmarshal(result, msg)
c.Expect(err, gs.IsNil)
c.Expect(msg.GetPayload(), gs.Equals, "mutated payload")
c.Expect(pack.Message.GetPayload(), gs.Equals, "original")
})
})
})
}
示例15: EncoderSpec
func EncoderSpec(c gs.Context) {
t := new(ts.SimpleT)
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// NewPipelineConfig sets up Globals which is needed for the
// pipeline.Prepend*Dir functions to not die during plugin Init().
pConfig := pipeline.NewPipelineConfig(nil)
c.Specify("A SandboxEncoder", func() {
encoder := new(SandboxEncoder)
encoder.SetPipelineConfig(pConfig)
conf := encoder.ConfigStruct().(*SandboxEncoderConfig)
supply := make(chan *pipeline.PipelinePack, 1)
pack := pipeline.NewPipelinePack(supply)
pack.Message.SetPayload("original")
pack.Message.SetType("my_type")
pack.Message.SetPid(12345)
pack.Message.SetSeverity(4)
pack.Message.SetHostname("hostname")
pack.Message.SetTimestamp(54321)
pack.Message.SetUuid(uuid.NewRandom())
var (
result []byte
err error
)
c.Specify("emits JSON correctly", func() {
conf.ScriptFilename = "../lua/testsupport/encoder_json.lua"
err = encoder.Init(conf)
c.Expect(err, gs.IsNil)
result, err = encoder.Encode(pack)
c.Expect(err, gs.IsNil)
msg := new(message.Message)
err = json.Unmarshal(result, msg)
c.Expect(err, gs.IsNil)
c.Expect(msg.GetTimestamp(), gs.Equals, int64(54321))
c.Expect(msg.GetPid(), gs.Equals, int32(12345))
c.Expect(msg.GetSeverity(), gs.Equals, int32(4))
c.Expect(msg.GetHostname(), gs.Equals, "hostname")
c.Expect(msg.GetPayload(), gs.Equals, "original")
c.Expect(msg.GetType(), gs.Equals, "my_type")
})
c.Specify("emits text correctly", func() {
conf.ScriptFilename = "../lua/testsupport/encoder_text.lua"
err = encoder.Init(conf)
c.Expect(err, gs.IsNil)
result, err = encoder.Encode(pack)
c.Expect(err, gs.IsNil)
c.Expect(string(result), gs.Equals, "Prefixed original")
})
c.Specify("emits protobuf correctly", func() {
c.Specify("when inject_message is used", func() {
conf.ScriptFilename = "../lua/testsupport/encoder_protobuf.lua"
err = encoder.Init(conf)
c.Expect(err, gs.IsNil)
result, err = encoder.Encode(pack)
c.Expect(err, gs.IsNil)
msg := new(message.Message)
err = proto.Unmarshal(result, msg)
c.Expect(err, gs.IsNil)
c.Expect(msg.GetTimestamp(), gs.Equals, int64(54321))
c.Expect(msg.GetPid(), gs.Equals, int32(12345))
c.Expect(msg.GetSeverity(), gs.Equals, int32(4))
c.Expect(msg.GetHostname(), gs.Equals, "hostname")
c.Expect(msg.GetPayload(), gs.Equals, "mutated")
c.Expect(msg.GetType(), gs.Equals, "after")
})
c.Specify("when `write_message` is used", func() {
conf.ScriptFilename = "../lua/testsupport/encoder_writemessage.lua"
err = encoder.Init(conf)
c.Expect(err, gs.IsNil)
result, err = encoder.Encode(pack)
c.Expect(err, gs.IsNil)
msg := new(message.Message)
err = proto.Unmarshal(result, msg)
c.Expect(err, gs.IsNil)
c.Expect(msg.GetPayload(), gs.Equals, "mutated payload")
c.Expect(pack.Message.GetPayload(), gs.Equals, "original")
})
})
})
c.Specify("cbuf librato encoder", func() {
encoder := new(SandboxEncoder)
encoder.SetPipelineConfig(pConfig)
conf := encoder.ConfigStruct().(*SandboxEncoderConfig)
supply := make(chan *pipeline.PipelinePack, 1)
pack := pipeline.NewPipelinePack(supply)
//.........這裏部分代碼省略.........