json: Add UnmarshalDisallowUnknownFields

This commit is contained in:
世界 2024-07-22 12:02:46 +08:00
parent 332e470075
commit 7893a74f75
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
4 changed files with 37 additions and 1 deletions

View file

@ -0,0 +1,12 @@
package json
func UnmarshalDisallowUnknownFields(data []byte, v any) error {
var d decodeState
d.disallowUnknownFields = true
err := checkValid(data, &d.scan)
if err != nil {
return err
}
d.init(data)
return d.unmarshal(v)
}

View file

@ -2,6 +2,7 @@ package json
import (
"bytes"
"errors"
"strings"
"github.com/sagernet/sing/common"
@ -15,7 +16,8 @@ func UnmarshalExtended[T any](content []byte) (T, error) {
if err == nil {
return value, err
}
if syntaxError, isSyntaxError := err.(*SyntaxError); isSyntaxError {
var syntaxError *SyntaxError
if errors.As(err, &syntaxError) {
prefix := string(content[:syntaxError.Offset])
row := strings.Count(prefix, "\n") + 1
column := len(prefix) - strings.LastIndex(prefix, "\n") - 1

View file

@ -0,0 +1,9 @@
//go:build go1.20 && !without_contextjson
package json
import (
json "github.com/sagernet/sing/common/json/internal/contextjson"
)
var UnmarshalDisallowUnknownFields = json.UnmarshalDisallowUnknownFields

View file

@ -0,0 +1,13 @@
//go:build !go1.20 || without_contextjson
package json
import (
"bytes"
)
func UnmarshalDisallowUnknownFields(content []byte, value any) error {
decoder := NewDecoder(bytes.NewReader(content))
decoder.DisallowUnknownFields()
return decoder.Decode(value)
}