added functions to read and write urls to the db modified opendb function to also open the word list modified fatal error function to close db before exiting
sophuwu sophie@sophuwu.site
Thu, 31 Aug 2023 20:25:37 +0100
1 files changed,
36 insertions(+),
5 deletions(-)
jump to
M
main.go
→
main.go
@@ -2,20 +2,31 @@ package main
import ( bolt "go.etcd.io/bbolt" + "math/rand" "os" + "strings" ) var urlDB *bolt.DB +var wordList []string func fec(err error) { // fatal error check if err != nil { println(err.Error()) + urlDB.Close() os.Exit(1) } } -func openDB() { - var err error +func openFiles() { + b, err := os.ReadFile("wordlist") + fec(err) + if len(b) == 0 { + println("wordlist is empty") + os.Exit(1) + } + wordList = strings.Split(string(b), "\n") + var db *bolt.DB db, err = bolt.Open("urls.db", 0600, nil) fec(err)@@ -27,10 +38,30 @@ urlDB = db
} func getWords() string { - + word := func() string { + return wordList[rand.Intn(len(wordList))] + } + return word() + "-" + word() + "-" + word() +} + +func readURL(words string) string { + var url string + _ = urlDB.View(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte("urls")) + url = string(b.Get([]byte(words))) + return nil + }) + return url +} + +func writeURL(words, url string) error { + return urlDB.Update(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte("urls")) + return b.Put([]byte(words), []byte(url)) + }) } func main() { - openDB() - defer urlDB.Close() + openFiles() + }