Skip to content
Snippets Groups Projects
Commit 9f0012d0 authored by Christian Pointner's avatar Christian Pointner
Browse files

added encoder/decoder for store.Log

parent 3c52279f
No related branches found
No related tags found
No related merge requests found
......@@ -25,11 +25,12 @@
package store
import (
"bytes"
"compress/gzip"
"encoding/json"
"io"
"sync"
"time"
"encoding/json"
)
type Log struct {
......@@ -51,6 +52,36 @@ func (l *Log) MarshalJSON() ([]byte, error) {
return json.Marshal(l.lines)
}
func (l *Log) encode() ([]byte, error) {
l.m.RLock()
defer l.m.RUnlock()
var buf bytes.Buffer
comp := gzip.NewWriter(&buf)
enc := json.NewEncoder(comp)
if err := enc.Encode(l.lines); err != nil {
return nil, err
}
if err := comp.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (l *Log) decode(data []byte) error {
l.m.RLock()
defer l.m.RUnlock()
l.lines = nil
buf := bytes.NewBuffer(data)
decomp, err := gzip.NewReader(buf)
if err != nil {
return err
}
dec := json.NewDecoder(decomp)
return dec.Decode(&l.lines)
}
func (l *Log) NewReader(stream string) *LogReader {
return &LogReader{l, -1, stream}
}
......
......@@ -29,6 +29,44 @@ import (
"testing"
)
func TestLogEncodeDecode(t *testing.T) {
var log1 Log
log1.Append("stdout", "this is a test")
log1.Append("stdout", "this is another test")
log1.Append("stderr", "oh no something went wrong!")
out, err := log1.encode()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var log2 Log
if err = log2.decode(out); err != nil {
t.Fatalf("unexpected error: %v", err)
}
// reflect.DeepEqual does not use time.Equal... so we have to do this by hand...
equal := false
if len(log1.lines) == len(log2.lines) {
for i := range log1.lines {
if log1.lines[i].Stream != log2.lines[i].Stream {
break
}
if log1.lines[i].Line != log2.lines[i].Line {
break
}
if !log1.lines[i].Timestamp.Equal(log2.lines[i].Timestamp) {
break
}
}
equal = true
}
if !equal {
t.Fatalf("logs are not equal: expected %+v, got %+v", log1.lines, log2.lines)
}
}
func TestLogReader(t *testing.T) {
var log Log
var buf [1024]byte
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment