記錄一下一些好用 golang library

blot 是一個純 golang 以簡單為美開發的 key value 資料庫,後來會用他,是因為一開始要存非常簡單的資料

想說就用 sqlite 來存就好了,反正欄位很少,資料結構簡單,開發環境是 Mac ,目標環境是 Linux ,部署的流程

就用 python 的 fabric 簡化,本地端編譯完 linux/amd64 的程式,複製到遠端 Linux,可是 github.com/mattn/go-sqlite3 有用到

CGO ,在 Mac 上面必須要用 gcc for linux 來編譯,編譯完後,到了目標機器上面又有 glibc 版本的問題,覺得這樣很花時間

不方便,另外就是 CGO 的編譯速度沒有很帥氣,立馬就決定找一個不依賴 CGO 的 key value store,目前覺得蠻合用了,這個專案的頁面的第一句話

就說服我了(我也太沒原則了吧) “Simple is the new beautiful.”

https://github.com/boltdb/bolt

使用簡單,由於我的 server  主要還是用簡單 JSON 格式,所以就先不用 gob 來 Encode 資料


// Example for bolt
package main

import (
“encoding/json”
“fmt”

“github.com/boltdb/bolt”
)

var (
db *bolt.DB
dbpath = “./user.db”
userbucket = []byte(“users”)
)

func main() {

db, _ = bolt.Open(dbpath, 0644, nil)

key := []byte(“unique_key_here”)
var value = struct {
Name string
Title string
}{“Somebody”, “Gopher”}

fmt.Println(key, value)

// in write transaction
err := db.Update(func(tx *bolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists(userbucket)
if err != nil {
return err
}
data, err := json.Marshal(value)

fmt.Println(“Please remember handle the error”, err)

if err == nil {
bucket.Put(key, data)
}

return nil
})

fmt.Println(err)
// in read
db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(userbucket)
if bucket != nil {
// if have a struct to restore it
//json.Unmarshal(bucket.Get([]byte(key)), &user)
fmt.Println(bucket.Get(key))
}

return nil
})

}