generated from ZEISS/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b490678
commit d7a4394
Showing
6 changed files
with
567 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,174 @@ | ||
package utilx | ||
|
||
import ( | ||
"reflect" | ||
"regexp" | ||
"strconv" | ||
"strings" | ||
"time" | ||
) | ||
|
||
// SetDefaults sets the default values for the fields of the given struct. | ||
// | ||
// Usage | ||
// | ||
// type ExampleBasic struct { | ||
// Foo bool `default:"true"` | ||
// Bar string `default:"33"` | ||
// Qux int8 | ||
// Dur time.Duration `default:"2m3s"` | ||
// } | ||
// | ||
// foo := &ExampleBasic{} | ||
// SetDefaults(foo) | ||
func SetDefaults(variable interface{}) { | ||
getDefaultFiller().Fill(variable) | ||
} | ||
|
||
var defaultFiller *Filler = nil | ||
|
||
func getDefaultFiller() *Filler { | ||
if defaultFiller == nil { | ||
defaultFiller = newDefaultFiller() | ||
} | ||
|
||
return defaultFiller | ||
} | ||
|
||
// nolint: exhaustive | ||
func newDefaultFiller() *Filler { | ||
funcs := make(map[reflect.Kind]FillerFunc, 0) | ||
funcs[reflect.Bool] = func(field *FieldData) { | ||
value, _ := strconv.ParseBool(field.TagValue) | ||
field.Value.SetBool(value) | ||
} | ||
|
||
funcs[reflect.Int] = func(field *FieldData) { | ||
value, _ := strconv.ParseInt(field.TagValue, 10, 64) | ||
field.Value.SetInt(value) | ||
} | ||
|
||
funcs[reflect.Int8] = funcs[reflect.Int] | ||
funcs[reflect.Int16] = funcs[reflect.Int] | ||
funcs[reflect.Int32] = funcs[reflect.Int] | ||
funcs[reflect.Int64] = func(field *FieldData) { | ||
if field.Field.Type == reflect.TypeOf(time.Second) { | ||
value, _ := time.ParseDuration(field.TagValue) | ||
field.Value.Set(reflect.ValueOf(value)) | ||
} else { | ||
value, _ := strconv.ParseInt(field.TagValue, 10, 64) | ||
field.Value.SetInt(value) | ||
} | ||
} | ||
|
||
funcs[reflect.Float32] = func(field *FieldData) { | ||
value, _ := strconv.ParseFloat(field.TagValue, 64) | ||
field.Value.SetFloat(value) | ||
} | ||
|
||
funcs[reflect.Float64] = funcs[reflect.Float32] | ||
|
||
funcs[reflect.Uint] = func(field *FieldData) { | ||
value, _ := strconv.ParseUint(field.TagValue, 10, 64) | ||
field.Value.SetUint(value) | ||
} | ||
|
||
funcs[reflect.Uint8] = funcs[reflect.Uint] | ||
funcs[reflect.Uint16] = funcs[reflect.Uint] | ||
funcs[reflect.Uint32] = funcs[reflect.Uint] | ||
funcs[reflect.Uint64] = funcs[reflect.Uint] | ||
|
||
funcs[reflect.String] = func(field *FieldData) { | ||
tagValue := parseDateTimeString(field.TagValue) | ||
field.Value.SetString(tagValue) | ||
} | ||
|
||
funcs[reflect.Struct] = func(field *FieldData) { | ||
fields := getDefaultFiller().GetFieldsFromValue(field.Value, nil) | ||
getDefaultFiller().SetDefaultValues(fields) | ||
} | ||
|
||
types := make(map[TypeHash]FillerFunc, 1) | ||
types["time.Duration"] = func(field *FieldData) { | ||
d, _ := time.ParseDuration(field.TagValue) | ||
field.Value.Set(reflect.ValueOf(d)) | ||
} | ||
|
||
funcs[reflect.Slice] = func(field *FieldData) { | ||
k := field.Value.Type().Elem().Kind() | ||
switch k { | ||
case reflect.Uint8: | ||
if field.Value.Bytes() != nil { | ||
return | ||
} | ||
field.Value.SetBytes([]byte(field.TagValue)) | ||
case reflect.Struct: | ||
count := field.Value.Len() | ||
for i := 0; i < count; i++ { | ||
fields := getDefaultFiller().GetFieldsFromValue(field.Value.Index(i), nil) | ||
getDefaultFiller().SetDefaultValues(fields) | ||
} | ||
default: | ||
// 处理形如 [1,2,3,4] | ||
reg := regexp.MustCompile(`^\[(.*)\]$`) | ||
matchs := reg.FindStringSubmatch(field.TagValue) | ||
if len(matchs) != 2 { | ||
return | ||
} | ||
if matchs[1] == "" { | ||
field.Value.Set(reflect.MakeSlice(field.Value.Type(), 0, 0)) | ||
} else { | ||
defaultValue := strings.Split(matchs[1], ",") | ||
result := reflect.MakeSlice(field.Value.Type(), len(defaultValue), len(defaultValue)) | ||
for i := 0; i < len(defaultValue); i++ { | ||
itemValue := result.Index(i) | ||
item := &FieldData{ | ||
Value: itemValue, | ||
Field: reflect.StructField{}, | ||
TagValue: defaultValue[i], | ||
Parent: nil, | ||
} | ||
funcs[k](item) | ||
} | ||
field.Value.Set(result) | ||
} | ||
} | ||
} | ||
|
||
return &Filler{FuncByKind: funcs, FuncByType: types, Tag: "default"} | ||
} | ||
|
||
func parseDateTimeString(data string) string { | ||
pattern := regexp.MustCompile(`\{\{(\w+\:(?:-|)\d*,(?:-|)\d*,(?:-|)\d*)\}\}`) | ||
matches := pattern.FindAllStringSubmatch(data, -1) // matches is [][]string | ||
for _, match := range matches { | ||
|
||
tags := strings.Split(match[1], ":") | ||
if len(tags) == 2 { | ||
|
||
valueStrings := strings.Split(tags[1], ",") | ||
if len(valueStrings) == 3 { | ||
var values [3]int | ||
for key, valueString := range valueStrings { | ||
num, _ := strconv.ParseInt(valueString, 10, 64) | ||
values[key] = int(num) | ||
} | ||
|
||
switch tags[0] { | ||
|
||
case "date": | ||
str := time.Now().AddDate(values[0], values[1], values[2]).Format("2006-01-02") | ||
data = strings.ReplaceAll(data, match[0], str) | ||
case "time": | ||
str := time.Now().Add((time.Duration(values[0]) * time.Hour) + | ||
(time.Duration(values[1]) * time.Minute) + | ||
(time.Duration(values[2]) * time.Second)).Format("15:04:05") | ||
data = strings.ReplaceAll(data, match[0], str) | ||
} | ||
} | ||
} | ||
|
||
} | ||
|
||
return data | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
package utilx | ||
|
||
import ( | ||
"testing" | ||
"time" | ||
|
||
"bou.ke/monkey" | ||
. "gopkg.in/check.v1" | ||
) | ||
|
||
// Hook up gocheck into the "go test" runner. | ||
|
||
func Test(t *testing.T) { | ||
monkey.Patch(time.Now, func() time.Time { | ||
t, _ := time.Parse("2006-01-02 15:04:05", "2020-06-10 12:00:00") | ||
return t | ||
}) | ||
|
||
TestingT(t) | ||
} | ||
|
||
type DefaultsSuite struct{} | ||
|
||
var _ = Suite(&DefaultsSuite{}) | ||
|
||
type Parent struct { | ||
Children []Child | ||
} | ||
|
||
type Child struct { | ||
Name string | ||
Age int `default:"10"` | ||
} | ||
|
||
type ExampleBasic struct { | ||
Bool bool `default:"true"` | ||
Integer int `default:"33"` | ||
Integer8 int8 `default:"8"` | ||
Integer16 int16 `default:"16"` | ||
Integer32 int32 `default:"32"` | ||
Integer64 int64 `default:"64"` | ||
UInteger uint `default:"11"` | ||
UInteger8 uint8 `default:"18"` | ||
UInteger16 uint16 `default:"116"` | ||
UInteger32 uint32 `default:"132"` | ||
UInteger64 uint64 `default:"164"` | ||
String string `default:"foo"` | ||
Bytes []byte `default:"bar"` | ||
Float32 float32 `default:"3.2"` | ||
Float64 float64 `default:"6.4"` | ||
Struct struct { | ||
Bool bool `default:"true"` | ||
Integer int `default:"33"` | ||
} | ||
Duration time.Duration `default:"1s"` | ||
Children []Child | ||
Second time.Duration `default:"1s"` | ||
StringSlice []string `default:"[1,2,3,4]"` | ||
IntSlice []int `default:"[1,2,3,4]"` | ||
IntSliceSlice [][]int `default:"[[1],[2],[3],[4]]"` | ||
StringSliceSlice [][]string `default:"[[1],[]]"` | ||
|
||
DateTime string `default:"{{date:1,-10,0}} {{time:1,-5,10}}"` | ||
} | ||
|
||
func (s *DefaultsSuite) TestSetDefaultsBasic(c *C) { | ||
foo := &ExampleBasic{} | ||
SetDefaults(foo) | ||
|
||
s.assertTypes(c, foo) | ||
} | ||
|
||
type ExampleNested struct { | ||
Struct ExampleBasic | ||
} | ||
|
||
func (s *DefaultsSuite) TestSetDefaultsNested(c *C) { | ||
foo := &ExampleNested{} | ||
SetDefaults(foo) | ||
|
||
s.assertTypes(c, &foo.Struct) | ||
} | ||
|
||
func (s *DefaultsSuite) assertTypes(c *C, foo *ExampleBasic) { | ||
c.Assert(foo.Bool, Equals, true) | ||
c.Assert(foo.Integer, Equals, 33) | ||
c.Assert(foo.Integer8, Equals, int8(8)) | ||
c.Assert(foo.Integer16, Equals, int16(16)) | ||
c.Assert(foo.Integer32, Equals, int32(32)) | ||
c.Assert(foo.Integer64, Equals, int64(64)) | ||
c.Assert(foo.UInteger, Equals, uint(11)) | ||
c.Assert(foo.UInteger8, Equals, uint8(18)) | ||
c.Assert(foo.UInteger16, Equals, uint16(116)) | ||
c.Assert(foo.UInteger32, Equals, uint32(132)) | ||
c.Assert(foo.UInteger64, Equals, uint64(164)) | ||
c.Assert(foo.String, Equals, "foo") | ||
c.Assert(string(foo.Bytes), Equals, "bar") | ||
c.Assert(foo.Float32, Equals, float32(3.2)) | ||
c.Assert(foo.Float64, Equals, 6.4) | ||
c.Assert(foo.Struct.Bool, Equals, true) | ||
c.Assert(foo.Duration, Equals, time.Second) | ||
c.Assert(foo.Children, IsNil) | ||
c.Assert(foo.Second, Equals, time.Second) | ||
c.Assert(foo.StringSlice, DeepEquals, []string{"1", "2", "3", "4"}) | ||
c.Assert(foo.IntSlice, DeepEquals, []int{1, 2, 3, 4}) | ||
c.Assert(foo.IntSliceSlice, DeepEquals, [][]int{{1}, {2}, {3}, {4}}) | ||
c.Assert(foo.StringSliceSlice, DeepEquals, [][]string{{"1"}, {}}) | ||
c.Assert(foo.DateTime, Equals, "2020-08-10 12:55:10") | ||
} | ||
|
||
func (s *DefaultsSuite) TestSetDefaultsWithValues(c *C) { | ||
foo := &ExampleBasic{ | ||
Integer: 55, | ||
UInteger: 22, | ||
Float32: 9.9, | ||
String: "bar", | ||
Bytes: []byte("foo"), | ||
Children: []Child{{Name: "alice"}, {Name: "bob", Age: 2}}, | ||
} | ||
|
||
SetDefaults(foo) | ||
|
||
c.Assert(foo.Integer, Equals, 55) | ||
c.Assert(foo.UInteger, Equals, uint(22)) | ||
c.Assert(foo.Float32, Equals, float32(9.9)) | ||
c.Assert(foo.String, Equals, "bar") | ||
c.Assert(string(foo.Bytes), Equals, "foo") | ||
c.Assert(foo.Children[0].Age, Equals, 10) | ||
c.Assert(foo.Children[1].Age, Equals, 2) | ||
} | ||
|
||
func (s *DefaultsSuite) BenchmarkLogic(c *C) { | ||
for i := 0; i < c.N; i++ { | ||
foo := &ExampleBasic{} | ||
SetDefaults(foo) | ||
} | ||
} |
Oops, something went wrong.