pkg/rest/codec/json.go

52 lines
957 B
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package codec
import (
"encoding/json/v2"
"fmt"
"io"
"net/http"
"strings"
)
type jsonCodec struct {
isJson bool
req *http.Request
}
// NewJsonCodec ...
func NewJsonCodec(r *http.Request) *jsonCodec {
isJson := false
// 限制Method, 同ParseForm的一致
contentType := r.Header.Get("Content-Type")
if (r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH") &&
strings.HasPrefix(contentType, "application/json") {
isJson = true
}
return &jsonCodec{req: r, isJson: isJson}
}
// Decode ...
func (j *jsonCodec) Decode(val any) error {
if !j.isJson {
return nil
}
body, err := io.ReadAll(j.req.Body)
if err != nil {
return err
}
// body等于空时可能其他解析场景直接正常返回
// 如果需要判断是否有值,可通过指针处理
if len(body) == 0 {
return nil
}
if err := json.Unmarshal(body, val); err != nil {
return fmt.Errorf("unmarshal json body: %w", err)
}
return nil
}