|
1 | 1 | package util |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "bytes" |
4 | 5 | "fmt" |
5 | 6 | "github.com/sjqzhang/goutil" |
| 7 | + "html/template" |
6 | 8 | "log" |
7 | 9 | "net" |
8 | 10 | "net/url" |
9 | 11 | "os" |
| 12 | + "path/filepath" |
10 | 13 | "reflect" |
11 | 14 | "regexp" |
12 | 15 | "runtime" |
@@ -99,6 +102,61 @@ func Parse(dsn string) (*DSN, error) { |
99 | 102 | return &d, nil |
100 | 103 | } |
101 | 104 |
|
| 105 | +// use go template to render string with map or list of map |
| 106 | +func Render(tpl string, data interface{}) (string, error) { |
| 107 | + t, err := template.New("tpl").Parse(tpl) |
| 108 | + if err != nil { |
| 109 | + return "", err |
| 110 | + } |
| 111 | + buf := new(bytes.Buffer) |
| 112 | + err = t.Execute(buf, data) |
| 113 | + if err != nil { |
| 114 | + return "", err |
| 115 | + } |
| 116 | + return buf.String(), nil |
| 117 | +} |
| 118 | + |
| 119 | + |
| 120 | +// parse string use regexp pattern with group and return map |
| 121 | +func ParseWithPattern(pattern, str string) (map[string]string, error) { |
| 122 | + reg,err := regexp.Compile(pattern) |
| 123 | + if err != nil { |
| 124 | + return nil, err |
| 125 | + } |
| 126 | + m := reg.FindStringSubmatch(str) |
| 127 | + if len(m) == 0 { |
| 128 | + return nil, fmt.Errorf("not match") |
| 129 | + } |
| 130 | + result := make(map[string]string) |
| 131 | + for i, name := range reg.SubexpNames() { |
| 132 | + if i != 0 && name != "" { |
| 133 | + result[name] = m[i] |
| 134 | + } |
| 135 | + } |
| 136 | + return result, nil |
| 137 | +} |
| 138 | + |
| 139 | + |
| 140 | + |
| 141 | + |
| 142 | +// get all files by suffix in a directory |
| 143 | +func GetFilesBySuffix(dir, suffix string) ([]string, error) { |
| 144 | + files := make([]string, 0) |
| 145 | + err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { |
| 146 | + if err != nil { |
| 147 | + return err |
| 148 | + } |
| 149 | + if !info.IsDir() && strings.HasSuffix(path, suffix) { |
| 150 | + files = append(files, path) |
| 151 | + } |
| 152 | + return nil |
| 153 | + }) |
| 154 | + if err != nil { |
| 155 | + return nil, err |
| 156 | + } |
| 157 | + return files, nil |
| 158 | +} |
| 159 | + |
102 | 160 |
|
103 | 161 | func CollectFieldNames(t reflect.Type,m map[string]struct{},prefix string) { |
104 | 162 | // Return if not struct or pointer to struct. |
|
0 commit comments