Go
Viper配置包
viper # go get github.com/spf13/viper 封装加载配置方法 # package configs import "github.com/spf13/viper" func LoadConfig(filepath string, encoding string, config interface{}) error { vp := viper.New() vp.SetConfigFile(filepath) vp.SetConfigType(encoding) err := vp.ReadInConfig() if err != nil { return err } return vp.Unmarshal(config) } func ReadConfig(filepath string, encoding string) (*viper.Viper, error) { vp := viper.New() vp.SetConfigFile(filepath) vp.SetConfigType(encoding) err := vp.ReadInConfig() return vp, err }
Go Sync包
WaitGroup # type WaitGroup func (wg *WaitGroup) Add(delta int) func (wg *WaitGroup) Done() func (wg *WaitGroup) Wait() package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup delta := 10 wg.Add(delta) for i := 1; i <= delta; i++ { go func(i int) { defer wg.Done() fmt.Println("handle ", i) }(i) } wg.Wait() fmt.Println("done") } Mutex # type Mutex func (m *Mutex) Lock() // 若锁正在被占用,则Lock()会被阻塞,直至锁被释放 func (m *Mutex) TryLock() bool // 尝试加锁,若锁被占用,则返回false,加锁失败 func (m *Mutex) Unlock() // 未被加锁的Mutex直接Unlock()则会fatal error: sync: unlock of unlocked mutex package main import ( "fmt" "sync" "time" ) func main() { var mu sync.Mutex m := make(map[string]int) for i := 1; i <= 10; i++ { go func(i int, m map[string]int) { mu.Lock() m["num"] += i mu.Unlock() }(i, m) } time.Sleep(5 * time.Second) fmt.Println(m) } RWMutex # type RWMutex func (rw *RWMutex) Lock() // 读写锁 func (rw *RWMutex) RLock() // 读锁 func (rw *RWMutex) RLocker() Locker func (rw *RWMutex) RUnlock() func (rw *RWMutex) TryLock() bool func (rw *RWMutex) TryRLock() bool func (rw *RWMutex) Unlock() 和 mutex 类似,只不过功能更多,可以只加读锁
Go Time包
时间转换 # func Now() Time // Now returns the current local time. func Unix(sec int64, nsec int64) Time func UnixMicro(usec int64) Time // Go v1.17 func UnixMilli(msec int64) Time // Go v1.17 func (t Time) Unix() int64 func (t Time) UnixMicro() int64 // Go v1.17 func (t Time) UnixMilli() int64 // Go v1.17 func (t Time) UnixNano() int64 // Go v1.17 func ParseInLocation(layout, value string, loc *Location) (Time, error) func (t Time) Format(layout string) string 获取当前时间戳 # package main import ( "fmt" "time" ) func main() { t := time.Now() // 当前时间 fmt.Println(t.Unix()) // 秒时间戳 fmt.Println(t.UnixMilli()) // 毫秒时间戳,Go V1.17新增 fmt.Println(t.UnixMicro()) // 微秒时间戳,Go V1.17新增 fmt.Println(t.UnixNano()) // 纳秒时间戳 } 时间戳转 string # 常用 time layout 常量