Skip to content

Commit

Permalink
feat: add reflectx
Browse files Browse the repository at this point in the history
  • Loading branch information
katallaxie authored Jan 14, 2025
1 parent d09b973 commit 54f4387
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
13 changes: 13 additions & 0 deletions reflectx/tags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package reflectx

import "strings"

// TagOptions ...
type TagOptions string

// ParseTag splits a struct field's json tag into its name and
// comma-separated options.
func ParseTag(tag string) (string, TagOptions) {
tag, opt, _ := strings.Cut(tag, ",")
return tag, TagOptions(opt)
}
40 changes: 40 additions & 0 deletions reflectx/tags_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package reflectx_test

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/zeiss/pkg/reflectx"
)

func TestParseTag(t *testing.T) {
t.Parallel()

tests := []struct {
tag string
expected string
expectedOptions reflectx.TagOptions
}{
{
tag: "name,omitempty",
expected: "name",
expectedOptions: "omitempty",
},
{
tag: "name,omitempty,required",
expected: "name",
expectedOptions: "omitempty,required",
},
{
tag: "name,omitempty,required,truncate",
expected: "name",
expectedOptions: "omitempty,required,truncate",
},
}

for _, test := range tests {
tag, opt := reflectx.ParseTag(test.tag)
assert.Equal(t, test.expected, tag)
assert.Equal(t, test.expectedOptions, opt)
}
}

0 comments on commit 54f4387

Please sign in to comment.