Skip to content

Commit

Permalink
Add general context of user data to reflect context (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
vearutop authored Apr 19, 2022
1 parent 21e261d commit 2ab12e6
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ linters-settings:
linters:
enable-all: true
disable:
- containedctx
- goerr113
- funlen
- gocognit
Expand Down
4 changes: 4 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package jsonschema

import (
"context"
"reflect"
"strings"

Expand Down Expand Up @@ -128,6 +129,9 @@ func ProcessWithoutTags(rc *ReflectContext) {

// ReflectContext accompanies single reflect operation.
type ReflectContext struct {
// Context allows communicating user data between reflection steps.
context.Context

// DefName returns custom definition name for a type, can be nil.
DefName func(t reflect.Type, defaultDefName string) string

Expand Down
2 changes: 2 additions & 0 deletions reflect.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package jsonschema

import (
"context"
"encoding"
"encoding/json"
"errors"
Expand Down Expand Up @@ -185,6 +186,7 @@ func checkSchemaSetup(v reflect.Value, s *Schema) (bool, error) {
// Titled, Described, Enum, NamedEnum.
func (r *Reflector) Reflect(i interface{}, options ...func(rc *ReflectContext)) (Schema, error) {
rc := ReflectContext{}
rc.Context = context.Background()
rc.DefinitionsPrefix = "#/definitions/"
rc.PropertyNameTag = "json"
rc.Path = []string{"#"}
Expand Down
22 changes: 22 additions & 0 deletions reflect_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package jsonschema_test

import (
"context"
"encoding"
"encoding/json"
"mime/multipart"
Expand Down Expand Up @@ -1070,3 +1071,24 @@ func TestReflector_Reflect_parentTagsFiltered(t *testing.T) {
}{})
assert.EqualError(t, err, "failed to parse int value abc in tag minProperties: strconv.ParseInt: parsing \"abc\": invalid syntax")
}

func TestReflector_Reflect_context(t *testing.T) {
type ctxKey struct{}

type Test struct {
Foo string `json:"foo"`
}

r := jsonschema.Reflector{}

_, err := r.Reflect(new(Test),
func(rc *jsonschema.ReflectContext) {
rc.Context = context.WithValue(rc.Context, ctxKey{}, true)
},
func(rc *jsonschema.ReflectContext) {
assert.Equal(t, true, rc.Value(ctxKey{}))
},
)

require.NoError(t, err)
}

0 comments on commit 2ab12e6

Please sign in to comment.