-
Notifications
You must be signed in to change notification settings - Fork 0
/
yaml4time.go
72 lines (60 loc) · 1.34 KB
/
yaml4time.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
/*
* @Author: dongzhzheng
* @Date: 2020-08-24 14:51:00
* @LastEditTime: 2020-09-22 15:15:43
* @LastEditors: dongzhzheng
* @FilePath: /recommend_item_embedding/common/yaml.go
* @Description:
*/
package utils
import (
"fmt"
"io/ioutil"
"os"
"strings"
"time"
yaml "gopkg.in/yaml.v3"
)
// YAMLDate 能从yaml解析出Date
type YAMLDate struct {
Time time.Time
}
// UnmarshalYAML 实现接口
func (t *YAMLDate) UnmarshalYAML(unmarshal func(interface{}) error) error {
var buf string
err := unmarshal(&buf)
if err != nil {
return nil
}
tt, err := time.Parse("2006-01-02", strings.TrimSpace(buf))
if err != nil {
return err
}
t.Time = tt
return nil
}
// MarshalYAML 实现接口
func (t YAMLDate) MarshalYAML() (interface{}, error) {
return t.Time.Format("2006-01-02"), nil
}
// ToString 返回字符串
func (t YAMLDate) ToString() string {
return t.Time.Format("2006-01-02")
}
// Set 设置
func (t *YAMLDate) Set(tm time.Time) {
t.Time = tm
}
// GetYAML 从yaml配置文件解析到struct
func GetYAML(f string, s interface{}) error {
ymlFile, err := os.Open(f)
if err != nil {
return fmt.Errorf("open yaml file(%s) failed: %v", f, err)
}
defer ymlFile.Close()
ymlContent, err := ioutil.ReadAll(ymlFile)
if err != nil {
return fmt.Errorf("read yaml file(%s) failed: %v", f, err)
}
return yaml.Unmarshal(ymlContent, s)
}