我正在尝试使用文件数据库 bbolt 作为键/值存储。下面是我的代码package handlerimport ( "encoding/json" "log" "net/http" "os" "go.etcd.io/bbolt" bolt "go.etcd.io/bbolt" yml "gopkg.in/yaml.v3")type urlDB struct { db *bbolt.DB}func (u urlDB) ensureDB() { u.db, _ = bolt.Open("url.db", 0600, nil)}func MapHandler(pathsToURLs map[string]string, fallback http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path if _, ok := pathsToURLs[path]; ok { http.Redirect(w, r, pathsToURLs[path], http.StatusFound) } else { fallback.ServeHTTP(w, r) } }}func DefaultMap(fallback http.Handler) http.HandlerFunc { db := urlDB{} db.ensureDB() //bkt := db.db.createBucket() //createSampleData(bkt) defer db.db.Close() bktName := "URLBucket" createBucket(db.db, bktName) addSampleData(db.db, bktName, "/gm", "https://mail.google.com") addSampleData(db.db, bktName, "/ym", "https://mail.yahoo.com") pathToURLs := make(map[string]string) getData(db.db, bktName, pathToURLs) return MapHandler(pathToURLs, fallback)}func createBucket(db *bbolt.DB, bktName string) { db.Update(func(tx *bbolt.Tx) error { _, _ = tx.CreateBucketIfNotExists([]byte(bktName)) return nil })}func addSampleData(db *bbolt.DB, bktName, key, value string) { db.Update(func(tx *bbolt.Tx) error { b := tx.Bucket([]byte(bktName)) _ = b.Put([]byte(key), []byte(value)) return nil })}func getData(db *bbolt.DB, bktName string, pathToURLs map[string]string) { db.View(func(tx *bbolt.Tx) error { b := tx.Bucket([]byte(bktName)) c := b.Cursor() for k, v := c.First(); k != nil; k, v = c.Next() { pathToURLs[string(k)] = string(v) } return nil })}因此,在handler:DefaultMap使用以下代码从 main.go调用它时mux := http.NewServeMux()var urlHandler http.HandlerFunc urlHandler = handler.DefaultMap(mux)http.ListenAndServe(":8080", urlHandler)
1 回答
慕慕森
TA贡献1856条经验 获得超17个赞
这一行:
github.com/xx/urlshortner/handler.createBucket(0x6c588d, {0x6c6358, 0xc000187ec8})
说错误在createBucket. 看着createBucket:
db.Update(func(tx *bbolt.Tx) error {
根据堆栈跟踪,它调用Update,并且db是这里唯一可以为 nil 的东西。
追踪回调,可以看到:
func (u urlDB) ensureDB() {
u.db, _ = bolt.Open("url.db", 0600, nil)
}
因此,db open 失败,并且u.db为 nil。
- 1 回答
- 0 关注
- 62 浏览
添加回答
举报
0/150
提交
取消