1
0
Fork 0
gobelt/README.md

1.8 KiB

Gobelt

Gobelt is a collection of Go tools.

Thread pool

import "github.com/localhots/gobelt/threadpool"
ctx := context.Background()
ctx, cancel = context.WithTimeout(ctx, 30*time.Second)
defer cancel()

pool := threadpool.New(10)
defer pool.Close()
for i := 0; i < 1000000; i++ {
    i := i
    pool.Enqueue(ctx, func() {
        fmt.Printf("The number is %d\n", i)
    })
}

File cache

import "github.com/localhots/gobelt/filecache"
ctx := context.Background()
var val int
filecache.Load(&val, "tmp/cache/items.json", func() interface{} {
    var items []Item
    err := conn.Query(ctx, "SELECT * FROM items").Load(&items).Error()
    if err != nil {
        log.Fatalf("Failed to load items: %v", err)
    }
    return items
})

Log

import "github.com/localhots/gobelt/log"
ctx := context.Background()
ctx = log.ContextWithFields(ctx, log.F{"email": params["email"]})

user, err := signup(ctx, params)
if err != nil {
    log.Errorf(ctx, "Signup failed: %v", err)
    // [ERRO] Signup failed: db: duplicate entry    email=bob@example.com
    return
}

log.Info(ctx, "New user signed up", log.F{"id": user.ID})
// [INFO] New user signed up    email=bob@example.com  id=14 

Set

There is a collection of packages implementing a set data type located inside the set package. Implemented types include:

  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • string

All the package names are type names prefixed with "set", e.g. setuint64.

import "github.com/localhots/gobelt/set/setstring"
s := setstring.New("one", "two")
s.Add("three")
s.Remove("one", "two").Add("four", "five")
fmt.Println("Size:", s.Len()) // 3
fmt.Println("Has one", s.Has("one"))
fmt.Println(s.SortedSlice()) // [three four five]