Skip to content

Commit

Permalink
json: Add UnmarshalDisallowUnknownFields
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Jul 22, 2024
1 parent 332e470 commit 7893a74
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 1 deletion.
12 changes: 12 additions & 0 deletions common/json/internal/contextjson/unmarshal.go
Original file line number Diff line number Diff line change
@@ -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)
}
4 changes: 3 additions & 1 deletion common/json/unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package json

import (
"bytes"
"errors"
"strings"

"github.com/sagernet/sing/common"
Expand All @@ -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
Expand Down
9 changes: 9 additions & 0 deletions common/json/unmarshal_context.go
Original file line number Diff line number Diff line change
@@ -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
13 changes: 13 additions & 0 deletions common/json/unmarshal_std.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 7893a74

Please sign in to comment.