♻️ Add tools.WriteValue
This commit is contained in:
parent
fd5d315164
commit
286ac4557d
4 changed files with 97 additions and 31 deletions
44
tools/write_buffer.go
Normal file
44
tools/write_buffer.go
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
package tools
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func WriteValue(buff *bytes.Buffer, val any) (n int, err error) {
|
||||
switch v := val.(type) {
|
||||
default:
|
||||
err = fmt.Errorf("Unsupported type %T", v)
|
||||
case nil:
|
||||
return
|
||||
case string:
|
||||
return buff.WriteString(v)
|
||||
case int:
|
||||
return buff.WriteString(strconv.Itoa(v))
|
||||
case int64:
|
||||
return buff.WriteString(strconv.FormatInt(v, 10))
|
||||
case float64:
|
||||
return buff.WriteString(strconv.FormatFloat(v, 'f', -1, 64))
|
||||
case json.Number:
|
||||
return buff.WriteString(v.String())
|
||||
case json.RawMessage:
|
||||
return buff.Write(v)
|
||||
case []byte:
|
||||
return buff.Write(v)
|
||||
case byte:
|
||||
err = buff.WriteByte(v)
|
||||
if err == nil {
|
||||
n = 1
|
||||
}
|
||||
case rune:
|
||||
return buff.WriteString(string(v))
|
||||
case bool:
|
||||
return buff.WriteString(strconv.FormatBool(v))
|
||||
case time.Time:
|
||||
return buff.WriteString(v.Format(time.RFC3339))
|
||||
}
|
||||
return
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue