generated from ElnuDev/go-project
Implement dictionary data serialization to improve startup times
This commit is contained in:
parent
3d21311f12
commit
91fb5d9e3b
2 changed files with 31 additions and 1 deletions
3
dict/.gitignore
vendored
3
dict/.gitignore
vendored
|
@ -1 +1,2 @@
|
|||
JMdict.xml
|
||||
JMdict.xml
|
||||
dict.bin
|
29
dict/main.go
29
dict/main.go
|
@ -1,6 +1,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
|
@ -16,6 +17,21 @@ import (
|
|||
var dict map[string]Entry
|
||||
|
||||
func LoadDict() error {
|
||||
// Loading from binary
|
||||
const binaryFile = "dict.bin"
|
||||
file, err := os.Open(binaryFile)
|
||||
if err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
defer file.Close()
|
||||
decoder := gob.NewDecoder(file)
|
||||
err = decoder.Decode(&dict)
|
||||
return err
|
||||
}
|
||||
|
||||
// Loading from JMdict
|
||||
const jmdictFile = "JMdict.xml"
|
||||
reader, err := os.Open(jmdictFile)
|
||||
if err != nil {
|
||||
|
@ -30,6 +46,19 @@ func LoadDict() error {
|
|||
entry := ParseEntry(&jmdictEntry)
|
||||
dict[entry.Kanji] = entry
|
||||
}
|
||||
|
||||
// Encoding to binary
|
||||
file, err = os.Create(binaryFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
encoder := gob.NewEncoder(file)
|
||||
err = encoder.Encode(&dict)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
Reference in a new issue