Golang 常用依赖
系统操作
github.com/tc-hib/go-winres
可对编译后的可执行文件进行图片修改、软件信息修改。
github.com/timandy/routine
routine
封装并提供了一些易用、无竞争、高性能的goroutine
上下文访问接口,它可以帮助你更优雅地访问协程上下文信息。
import (
"fmt"
"time"
"github.com/timandy/routine"
)
func main() {
goid := routine.Goid()
fmt.Printf("cur goid: %v\n", goid)
go func() {
goid := routine.Goid()
fmt.Printf("sub goid: %v\n", goid)
}()
// 等待子协程执行完。
time.Sleep(time.Second)
}
工具类合集
github.com/jinzhu/copier
复制
copier.Copy(&struct1, &struct2)
github.com/projectdiscovery/utils
包含多种工具,类似 Java 中的 Hutool 工具包。
github.com/projectdiscovery/utils/strings
字符串操作
github.com/projectdiscovery/retryablehttp-go
基于标准net/http客户端库开发的HTTP客户端接口,具有自动重试和指数回退功能。
github.com/projectdiscovery/fileutil
文件操作
github.com/projectdiscovery/ratelimit
访问速率限制
package main
import (
"context"
"fmt"
"time"
"github.com/projectdiscovery/ratelimit"
)
func main() {
// create a rate limiter by passing context, max tasks/requests , time interval
limiter := ratelimit.New(context.Background(), 5, time.Duration(10*time.Second))
save := time.Now()
for i := 0; i < 10; i++ {
// run limiter.Take() method before each task
limiter.Take()
fmt.Printf("Task %v completed after %v\n", i, time.Since(save))
}
/*
Output:
Task 0 completed after 4.083µs
Task 1 completed after 111.416µs
Task 2 completed after 118µs
Task 3 completed after 121.083µs
Task 4 completed after 124.583µs
Task 5 completed after 10.001356375s
Task 6 completed after 10.001524791s
Task 7 completed after 10.001537583s
Task 8 completed after 10.001542708s
Task 9 completed after 10.001548666s
*/
}
github.com/uniplaces/carbon
参考 PHP Carbon 的 Golang 版时间操作扩展。
import (
"fmt"
"time"
"github.com/uniplaces/carbon"
)
func main() {
fmt.Printf("Right now is %s\n", carbon.Now().DateTimeString())
today, _ := carbon.NowInLocation("America/Vancouver")
fmt.Printf("Right now in Vancouver is %s\n", today)
fmt.Printf("Tomorrow is %s\n", carbon.Now().AddDay())
fmt.Printf("Last week is %s\n", carbon.Now().SubWeek())
nextOlympics, _ := carbon.CreateFromDate(2016, time.August, 5, "Europe/London")
nextOlympics = nextOlympics.AddYears(4)
fmt.Printf("Next olympics are in %d\n", nextOlympics.Year())
if carbon.Now().IsWeekend() {
fmt.Printf("Party time!")
}
}
github.com/jinzhu/now
基于当前时间计算指定类型时间
import "github.com/jinzhu/now"
time.Now() // 2013-11-18 17:51:49.123456789 Mon
now.BeginningOfMinute() // 2013-11-18 17:51:00 Mon
now.BeginningOfHour() // 2013-11-18 17:00:00 Mon
now.BeginningOfDay() // 2013-11-18 00:00:00 Mon
now.BeginningOfWeek() // 2013-11-17 00:00:00 Sun
now.BeginningOfMonth() // 2013-11-01 00:00:00 Fri
now.BeginningOfQuarter() // 2013-10-01 00:00:00 Tue
now.BeginningOfYear() // 2013-01-01 00:00:00 Tue
now.EndOfMinute() // 2013-11-18 17:51:59.999999999 Mon
now.EndOfHour() // 2013-11-18 17:59:59.999999999 Mon
now.EndOfDay() // 2013-11-18 23:59:59.999999999 Mon
now.EndOfWeek() // 2013-11-23 23:59:59.999999999 Sat
now.EndOfMonth() // 2013-11-30 23:59:59.999999999 Sat
now.EndOfQuarter() // 2013-12-31 23:59:59.999999999 Tue
now.EndOfYear() // 2013-12-31 23:59:59.999999999 Tue
now.WeekStartDay = time.Monday // Set Monday as first day, default is Sunday
now.EndOfWeek() // 2013-11-24 23:59:59.999999999 Sun
github.com/spf13/cast
数据类型转换
cast.ToString("mayonegg") // "mayonegg"
cast.ToString(8) // "8"
cast.ToString(8.31) // "8.31"
cast.ToString([]byte("one time")) // "one time"
cast.ToString(nil) // ""
var foo interface{} = "one more time"
cast.ToString(foo) // "one more time"
cast.ToInt(8) // 8
cast.ToInt(8.31) // 8
cast.ToInt("8") // 8
cast.ToInt(true) // 1
cast.ToInt(false) // 0
var eight interface{} = 8
cast.ToInt(eight) // 8
cast.ToInt(nil) // 0
对象转换
github.com/stretchr/objx
JSON转对象
// Use MustFromJSON to make an objx.Map from some JSON
m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`)
// Get the details
name := m.Get("name").Str()
age := m.Get("age").Int()
// Get their nickname (or use their name if they don't have one)
nickname := m.Get("nickname").Str(name)
github.com/goccy/go-json
与 encoding/json
兼容的快速JSON编码器/解码器
-import "encoding/json"
+import "github.com/goccy/go-json"
缓存
github.com/projectdiscovery/hmap
混合内存/磁盘映射,可帮助您管理用于输入重复数据消除的关键价值存储。
Name | Props |
---|---|
DefaultOptions | - Type: Memory - MemoryExpirationTime: time.Duration(5) * time.Minute - JanitorTime: time.Duration(1) * time.Minute |
DefaultMemoryOptions | - Type: Memory |
DefaultDiskOptions | - Type: Disk - DBType: LevelDB - Cleanup: true - RemoveOlderThan: 24* time.Hour *2 |
DefaultDiskOptions | - Type: Hybrid - DBType: PogrebDB - MemoryExpirationTime: time.Duration(5) * time.Minute - JanitorTime: time.Duration(1) * time.Minute |
func main() {
var wg sync.WaitGroup
wg.Add(1)
go normal(&wg)
wg.Wait()
}
func normal(wg *sync.WaitGroup) {
defer wg.Done()
hm, err := hybrid.New(hybrid.DefaultOptions)
if err != nil {
log.Fatal(err)
}
defer hm.Close()
err2 := hm.Set("a", []byte("b"))
if err2 != nil {
log.Fatal(err2)
}
v, ok := hm.Get("a")
if ok {
log.Println(v)
}
}
文件操作
github.com/spf13/afero
Afero是一个文件系统框架,提供了一个简单、统一和通用的API与任何文件系统交互,作为提供接口、类型和方法的抽象层。Afero有一个异常干净的接口和简单的设计,没有不必要的构造函数或初始化方法。
github.com/joho/godotenv
对项目配置文件的操作,默认为根目录的 .env 文件。
// .env
// S3_BUCKET=YOURS3BUCKET
// SECRET_KEY=YOURSECRETKEYGOESHERE
import (
"log"
"os"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
s3Bucket := os.Getenv("S3_BUCKET")
secretKey := os.Getenv("SECRET_KEY")
// now do something with s3 or whatever
}
// godotenv.Load("somerandomfile")
// godotenv.Load("filenumberone.env", "filenumbertwo.env")
CLI
github.com/spf13/cobra
Cobra是一个用于创建强大的现代CLI应用程序的库。 Cobra用于许多Go项目,例如Kubernetes、Hugo和GitHub CLI等。该列表包含使用Cobra的更广泛的项目列表。
github.com/bep/simplecobra
Cobra是一个Go CLI库,其功能集对于大型应用程序来说难以抗拒(自动完成、文档和手册页自动生成等)。)
但是除了最简单的应用程序之外,它的使用也很复杂。这个包是为了帮助重写Hugo的命令包,使其更容易理解和维护。
错误
github.com/pkg/errors
包错误提供了简单的错误处理原语,该包允许程序员以不破坏错误原始值的方式向代码中的失败路径添加上下文。
_, err := ioutil.ReadAll(r)
if err != nil {
return errors.Wrap(err, "read failed")
}
//...
switch err := errors.Cause(err).(type) {
case *MyError:
// handle specifically
default:
// unknown error
}
测试
github.com/stretchr/testify
Go代码(golang)包集,提供了许多工具来证明您的代码将按照您的意愿运行。