diff options
| author | Felix Hanley <felix@userspace.com.au> | 2019-09-18 02:12:47 +0000 |
|---|---|---|
| committer | Felix Hanley <felix@userspace.com.au> | 2019-09-18 02:12:47 +0000 |
| commit | 508d216990565cb9ec19790c05d875e6f3521a5e (patch) | |
| tree | 3699b79537902d5718db002cb0b3493985b9e23e | |
| parent | c3d2f9bf897e52249644bd239ee1696ff374ca8f (diff) | |
| download | logger-508d216990565cb9ec19790c05d875e6f3521a5e.tar.gz logger-508d216990565cb9ec19790c05d875e6f3521a5e.tar.bz2 | |
Add time and Stringer to string handling
| -rw-r--r-- | internal/strings.go | 12 | ||||
| -rw-r--r-- | internal/strings_test.go | 19 |
2 files changed, 30 insertions, 1 deletions
diff --git a/internal/strings.go b/internal/strings.go index 9b8b802..8924734 100644 --- a/internal/strings.go +++ b/internal/strings.go @@ -3,13 +3,19 @@ package internal import ( "fmt" "strconv" + "time" ) // ToString converts interface to string func ToString(v interface{}) string { + if v == nil { + return "" + } switch c := v.(type) { case string: return c + case *string: + return *c case int: return strconv.FormatInt(int64(c), 10) case int64: @@ -36,6 +42,12 @@ func ToString(v interface{}) string { return strconv.FormatFloat(c, 'g', -1, 64) case bool: return strconv.FormatBool(c) + case *bool: + return strconv.FormatBool(*c) + case *time.Time: + return fmt.Sprintf("%s", c) + case fmt.Stringer: + return c.String() default: return fmt.Sprintf("%v", c) } diff --git a/internal/strings_test.go b/internal/strings_test.go index 418ed50..4f1a0c8 100644 --- a/internal/strings_test.go +++ b/internal/strings_test.go @@ -2,9 +2,19 @@ package internal import ( "testing" + "time" ) +type stringer struct{} + +func (s stringer) String() string { + return "I am a stringer" +} + func TestToString(t *testing.T) { + epoch := time.Date(0, 0, 0, 0, 0, 0, 0, time.UTC) + s := "string" + b := true tests := []struct { in interface{} expected string @@ -25,7 +35,14 @@ func TestToString(t *testing.T) { {uint64(30), "30"}, {float32(3.0001), "3.0001"}, {float64(3.0000001), "3.0000001"}, - {nil, "<nil>"}, + {nil, ""}, + {new(stringer), "I am a stringer"}, + {epoch, "-0001-11-30 00:00:00 +0000 UTC"}, + {struct{ string }{"test"}, "{test}"}, + // Pointers + {&s, "string"}, + {&epoch, "-0001-11-30 00:00:00 +0000 UTC"}, + {&b, "true"}, } for _, tt := range tests { |
