✨ Add Meta with TextMarshaler
This commit is contained in:
parent
c61c783c66
commit
3cfb1ccedb
2 changed files with 106 additions and 0 deletions
|
|
@ -1 +1,53 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Meta struct {
|
||||
Key string
|
||||
Value any
|
||||
}
|
||||
|
||||
func (m Meta) MarshalText() ([]byte, error) {
|
||||
if regexp.MustCompile(`\s`).MatchString(m.Key) {
|
||||
return []byte{}, fmt.Errorf("whitespace is now allowed in key: %s", m.Key)
|
||||
}
|
||||
buff := &bytes.Buffer{}
|
||||
buff.WriteRune('@')
|
||||
buff.WriteString(m.Key)
|
||||
buff.WriteRune(' ')
|
||||
switch v := m.Value.(type) {
|
||||
default:
|
||||
return nil, fmt.Errorf("Unknown type %T", v)
|
||||
case nil:
|
||||
return []byte{}, nil
|
||||
case string:
|
||||
buff.WriteString(v)
|
||||
case int:
|
||||
buff.WriteString(strconv.Itoa(v))
|
||||
case float64:
|
||||
buff.WriteString(strconv.FormatFloat(v, 'f', -1, 64))
|
||||
case json.Number:
|
||||
buff.WriteString(v.String())
|
||||
case json.RawMessage:
|
||||
buff.Write(v)
|
||||
case []byte:
|
||||
buff.Write(v)
|
||||
case byte:
|
||||
buff.WriteByte(v)
|
||||
case rune:
|
||||
buff.WriteString(string(v))
|
||||
case bool:
|
||||
buff.WriteString(strconv.FormatBool(v))
|
||||
case time.Time:
|
||||
buff.WriteString(v.Format(time.RFC3339))
|
||||
}
|
||||
|
||||
return buff.Bytes(), nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue