-
Notifications
You must be signed in to change notification settings - Fork 0
/
tag.go
112 lines (95 loc) · 2.39 KB
/
tag.go
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
102
103
104
105
106
107
108
109
110
111
112
/*
* Copyright 2024 hopeio. All rights reserved.
* Licensed under the MIT License that can be found in the LICENSE file.
* @Created by jyb
*/
package initialize
import (
"fmt"
"github.com/hopeio/utils/log"
"github.com/hopeio/utils/reflect/structtag"
stringsi "github.com/hopeio/utils/strings"
"reflect"
"strings"
)
// example:
/*
type Dao struct {
DB mysql.DB `init:"config:MysqlTest"`
}
type Config struct {
Env string
}
*/
const (
initTagName = "init"
exprTagName = "expr"
metaTagName = "meta"
)
type InitTagSettings struct {
ConfigName string `meta:"config"`
DefaultValue string `meta:"default"`
}
func ParseInitTagSettings(str string) *InitTagSettings {
if str == "" {
return &InitTagSettings{}
}
var settings InitTagSettings
ParseTagSetting(str, ";", &settings)
return &settings
}
// ParseTagSetting default sep ;
func ParseTagSetting(str string, sep string, settings any) {
err := structtag.ParseTagSettingIntoStruct(str, sep, settings, metaTagName)
if err != nil {
log.Fatal(err)
}
}
func genEncodingTag(name string) string {
return fmt.Sprintf(`json:"%s" toml:"%s" yaml:"%s"`, name, name, name)
}
// get field name, return filed config name and skip flag
func getFieldConfigName(v reflect.StructField) (string, tagOptions, bool) {
tag := v.Tag.Get("mapstructure")
if tag == "" {
return v.Name, "", true
}
if tag == "-" {
return "", "", false
}
name, opts := parseTag(tag)
if name == "" {
return v.Name, opts, true
}
return stringsi.UpperCaseFirst(name), opts, true
}
// tagOptions is the string following a comma in a struct field's "json"
// tag, or the empty string. It does not include the leading comma.
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)
}
// Contains reports whether a comma-separated list of options
// contains a particular substr flag. substr must be surrounded by a
// string boundary or commas.
func (o tagOptions) Contains(optionName string) bool {
if len(o) == 0 {
return false
}
s := string(o)
for s != "" {
var name string
name, s, _ = strings.Cut(s, ",")
if name == optionName {
return true
}
}
return false
}
// 整合viper,提供单个注入,viper实现也挺简单的,原来的方案就能实现啊
/*func Inject(v Config, path string) {
}
*/