✨ Add JSON formatter
This commit is contained in:
parent
d1b3604e1e
commit
4c0edcd1a5
4 changed files with 132 additions and 1 deletions
63
formatters/json.go
Normal file
63
formatters/json.go
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
package formatters
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"codeberg.org/danjones000/my-log/config"
|
||||
"codeberg.org/danjones000/my-log/models"
|
||||
//"codeberg.org/danjones000/my-log/tools"
|
||||
)
|
||||
|
||||
func newJson(ff config.Formatters) (Formatter, error) {
|
||||
// @todo pretty print
|
||||
return &Json{ff.Json()}, nil
|
||||
}
|
||||
|
||||
type Json struct {
|
||||
jf config.JsonFormat
|
||||
}
|
||||
|
||||
func (js *Json) Name() string {
|
||||
return "json"
|
||||
}
|
||||
|
||||
func (js *Json) Meta(m models.Meta) ([]byte, error) {
|
||||
o := map[string]any{m.Key: m.Value}
|
||||
return json.Marshal(o)
|
||||
}
|
||||
|
||||
func (js *Json) entryMap(e models.Entry) map[string]any {
|
||||
o := map[string]any{
|
||||
"title": e.Title,
|
||||
"date": e.Date.Format(time.RFC3339),
|
||||
}
|
||||
for _, m := range e.Fields {
|
||||
o[m.Key] = m.Value
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func (js *Json) Entry(e models.Entry) ([]byte, error) {
|
||||
return json.Marshal(js.entryMap(e))
|
||||
}
|
||||
|
||||
func (js *Json) Log(l models.Log) ([]byte, error) {
|
||||
return js.Logs([]models.Log{l})
|
||||
}
|
||||
|
||||
func (js *Json) Logs(logs []models.Log) (out []byte, err error) {
|
||||
if len(logs) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
o := map[string][]map[string]any{}
|
||||
for _, l := range logs {
|
||||
es := []map[string]any{}
|
||||
for _, e := range l.Entries {
|
||||
es = append(es, js.entryMap(e))
|
||||
}
|
||||
o[l.Name] = es
|
||||
}
|
||||
return json.Marshal(o)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue