MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+68
@@ -0,0 +1,68 @@
|
||||
# Package `json`
|
||||
|
||||
Пакет `json` расширяет библиотеку [jsoniter](https://github.com/json-iterator/go) с дополнительными возможностями:
|
||||
|
||||
- Кастомное форматирование времени
|
||||
- Автоматическое преобразование имен полей camelCase, если не указан json тэг у структуры
|
||||
- Совместимость с API стандартной библиотеки `encoding/json`
|
||||
|
||||
## Functions
|
||||
|
||||
#### `Marshal(v any) ([]byte, error)`
|
||||
|
||||
Преобразовать переданный объект в массив байт json-формата.
|
||||
|
||||
#### `Unmarshal(data []byte, ptr any) error`
|
||||
|
||||
Преобразовать объект обратно из массива байт json-формата.
|
||||
|
||||
#### `NewEncoder(w io.Writer) *jsoniter.Encoder`
|
||||
|
||||
Создание потокового энкодера.
|
||||
|
||||
#### `NewDecoder(r io.Reader) *jsoniter.Decoder`
|
||||
|
||||
Создание потокового декодера.
|
||||
|
||||
#### `EncodeInto(w io.Writer, value any) error`
|
||||
|
||||
Оптимизированная запись в поток с автоматическим сбросом буфера
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func main() {
|
||||
msg := Message{
|
||||
Text: "hi x.x",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
/* data: {"text":"hi x.x","createdAt":"2009-11-10T23:00:00Z"} */
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var decoded Message
|
||||
err = json.Unmarshal(data, &decoded)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
// Package json provides a high-performance JSON encoder/decoder based on jsoniter.
|
||||
//
|
||||
// It extends the standard library with:
|
||||
// - Custom time.Time formatting (RFC3339 with milliseconds)
|
||||
// - Automatic camelCase conversion for struct field names
|
||||
// - Full API compatibility with encoding/json
|
||||
//
|
||||
// This package is safe for concurrent use by multiple goroutines.
|
||||
package json
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
|
||||
"github.com/json-iterator/go"
|
||||
"github.com/modern-go/reflect2"
|
||||
)
|
||||
|
||||
// RawMessage is a raw encoded JSON value. It implements Marshaler and
|
||||
// Unmarshaler and can be used to delay JSON decoding or precompute a JSON
|
||||
// encoding. It is an alias for encoding/json.RawMessage.
|
||||
type RawMessage = json.RawMessage
|
||||
|
||||
// instance is the shared jsoniter configuration with time and naming extensions.
|
||||
// nolint:gochecknoglobals
|
||||
var (
|
||||
instance = jsoniter.ConfigDefault
|
||||
)
|
||||
|
||||
// init registers the custom time codec and camelCase naming strategy extensions.
|
||||
// nolint:gochecknoinits
|
||||
func init() {
|
||||
timeType := reflect2.TypeByName("time.Time")
|
||||
tc := NewTimeCodec(FullDateFormat)
|
||||
encExt := jsoniter.EncoderExtension{timeType: tc}
|
||||
decExt := jsoniter.DecoderExtension{timeType: tc}
|
||||
instance.RegisterExtension(encExt)
|
||||
instance.RegisterExtension(decExt)
|
||||
|
||||
naming := &namingStrategyExtension{jsoniter.DummyExtension{}, lowerCaseFirstChar}
|
||||
instance.RegisterExtension(naming)
|
||||
}
|
||||
|
||||
// Marshal returns the JSON encoding of v.
|
||||
//
|
||||
// It uses the default jsoniter configuration with time formatting and camelCase field naming.
|
||||
func Marshal(v any) ([]byte, error) {
|
||||
return instance.Marshal(v)
|
||||
}
|
||||
|
||||
// Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by ptr.
|
||||
//
|
||||
// See encoding/json.Unmarshal for details on the conversion.
|
||||
func Unmarshal(data []byte, ptr any) error {
|
||||
return instance.Unmarshal(data, ptr)
|
||||
}
|
||||
|
||||
// NewEncoder returns a new encoder that writes to w.
|
||||
func NewEncoder(w io.Writer) *jsoniter.Encoder {
|
||||
return instance.NewEncoder(w)
|
||||
}
|
||||
|
||||
// NewDecoder returns a new decoder that reads from r.
|
||||
func NewDecoder(r io.Reader) *jsoniter.Decoder {
|
||||
return instance.NewDecoder(r)
|
||||
}
|
||||
|
||||
// EncodeInto encodes a value into a writer, appending a newline.
|
||||
//
|
||||
// This is an optimized function for line-delimited JSON (e.g., NDJSON).
|
||||
func EncodeInto(w io.Writer, value any) error {
|
||||
stream := instance.BorrowStream(w)
|
||||
defer instance.ReturnStream(stream)
|
||||
stream.WriteVal(value)
|
||||
stream.WriteRaw("\n")
|
||||
stream.Flush()
|
||||
return stream.Error
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package json
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/json-iterator/go"
|
||||
)
|
||||
|
||||
// namingStrategyExtension is a jsoniter extension that converts exported struct field
|
||||
// names from PascalCase to camelCase during JSON serialization/deserialization.
|
||||
//
|
||||
// It skips fields that:
|
||||
// - Start with a lowercase letter or underscore
|
||||
// - Have an explicit "json" tag (non-empty or "-")
|
||||
type namingStrategyExtension struct {
|
||||
jsoniter.DummyExtension
|
||||
|
||||
translate func(string) string
|
||||
}
|
||||
|
||||
// UpdateStructDescriptor modifies the field naming for struct serialization.
|
||||
//
|
||||
// It converts exported field names (starting with uppercase letter) to camelCase,
|
||||
// unless they have an explicit JSON tag.
|
||||
func (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
|
||||
for _, binding := range structDescriptor.Fields {
|
||||
if unicode.IsLower(rune(binding.Field.Name()[0])) || binding.Field.Name()[0] == '_' {
|
||||
continue
|
||||
}
|
||||
tag, hastag := binding.Field.Tag().Lookup("json")
|
||||
if hastag {
|
||||
tagParts := strings.Split(tag, ",")
|
||||
if tagParts[0] == "-" {
|
||||
continue // hidden field
|
||||
}
|
||||
if tagParts[0] != "" {
|
||||
continue // field explicitly named
|
||||
}
|
||||
}
|
||||
binding.ToNames = []string{extension.translate(binding.Field.Name())}
|
||||
binding.FromNames = []string{extension.translate(binding.Field.Name())}
|
||||
}
|
||||
}
|
||||
|
||||
// lowerCaseFirstChar converts the first character of a string to lowercase.
|
||||
//
|
||||
// It is used for camelCase conversion (e.g., "FirstName" → "firstName").
|
||||
func lowerCaseFirstChar(s string) string {
|
||||
for i, v := range s {
|
||||
return string(unicode.ToLower(v)) + s[i+1:]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package json
|
||||
|
||||
import (
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
)
|
||||
|
||||
// FullDateFormat is the default layout for time.Time serialization.
|
||||
//
|
||||
// It uses RFC3339 with millisecond precision: "2006-01-02T15:04:05.999Z07:00"
|
||||
const (
|
||||
FullDateFormat = "2006-01-02T15:04:05.999Z07:00"
|
||||
)
|
||||
|
||||
// TimeCodec is a jsoniter extension for custom time.Time encoding and decoding.
|
||||
//
|
||||
// It formats time values using a configurable layout string.
|
||||
type TimeCodec struct {
|
||||
format string
|
||||
}
|
||||
|
||||
// NewTimeCodec returns a new TimeCodec with the specified format layout.
|
||||
//
|
||||
// The format string follows Go's time.Parse conventions (see time.Layout).
|
||||
func NewTimeCodec(format string) *TimeCodec {
|
||||
return &TimeCodec{format: format}
|
||||
}
|
||||
|
||||
// Decode parses a JSON string into a time.Time value.
|
||||
//
|
||||
// It reports an error to the iterator if the string cannot be parsed.
|
||||
func (codec *TimeCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||
t, err := time.Parse(codec.format, iter.ReadString())
|
||||
if err != nil {
|
||||
iter.ReportError("string -> time.Time", err.Error())
|
||||
} else {
|
||||
*((*time.Time)(ptr)) = t
|
||||
}
|
||||
}
|
||||
|
||||
// IsEmpty checks if a time.Time value is zero.
|
||||
//
|
||||
// It returns true if the time is the zero value.
|
||||
func (codec *TimeCodec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||
ts := *((*time.Time)(ptr))
|
||||
return ts.IsZero()
|
||||
}
|
||||
|
||||
// Encode writes a time.Time value as a formatted JSON string.
|
||||
//
|
||||
// The time is formatted using the codec's layout string.
|
||||
func (codec *TimeCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
|
||||
ts := *((*time.Time)(ptr))
|
||||
stream.WriteString(ts.Format(codec.format))
|
||||
}
|
||||
Reference in new issue
Block a user