-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_encode.go
More file actions
101 lines (78 loc) · 1.6 KB
/
string_encode.go
File metadata and controls
101 lines (78 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* Copyright (c) 2026 Mikhail Knyazhev <markus621@yandex.com>. All rights reserved.
* Use of this source code is governed by a BSD 3-Clause license that can be found in the LICENSE file.
*/
package cast
import (
"encoding"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"reflect"
"time"
)
func StringEncode(obj any) (s string, err error) {
if obj == nil {
return
}
ref := reflect.ValueOf(obj)
if ref.Kind() == reflect.Ptr && ref.IsNil() {
return
}
switch v := obj.(type) {
case string:
s = v
case []byte:
s = string(v)
case int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64,
float32, float64,
bool:
s = fmt.Sprintf("%v", v)
case time.Duration:
s = v.String()
case time.Time:
s = v.Format(time.RFC3339)
case io.Reader:
var b []byte
b, err = io.ReadAll(v)
s = string(b)
case Byter:
s = string(v.Bytes())
case Stringer:
s = v.String()
case fmt.GoStringer:
s = v.GoString()
case encoding.BinaryMarshaler:
var b []byte
b, err = v.MarshalBinary()
s = string(b)
case encoding.TextMarshaler:
var b []byte
b, err = v.MarshalText()
s = string(b)
case json.Marshaler:
var b []byte
b, err = v.MarshalJSON()
s = string(b)
case xml.Marshaler:
var b []byte
b, err = xml.Marshal(v)
s = string(b)
case error:
s = v.Error()
default:
switch ref.Kind() {
case reflect.Ptr:
return StringEncode(ref.Elem().Interface())
case reflect.Struct, reflect.Map, reflect.Array, reflect.Slice:
var b []byte
b, err = json.Marshal(obj)
s = string(b)
default:
err = fmt.Errorf("unsupported type: %T", obj)
}
}
return
}