1
0
mirror of https://github.com/zu1k/nali.git synced 2025-01-22 21:29:02 +08:00
nali/internal/db/db.go

84 lines
1.6 KiB
Go
Raw Normal View History

2021-08-02 12:01:25 +08:00
package db
import (
"log"
2021-10-26 13:23:05 +08:00
"strings"
2021-08-02 12:01:25 +08:00
"github.com/spf13/viper"
2021-08-02 12:01:25 +08:00
"github.com/zu1k/nali/pkg/cdn"
"github.com/zu1k/nali/pkg/dbif"
2021-08-11 17:52:26 +08:00
"github.com/zu1k/nali/pkg/geoip"
2021-08-02 12:01:25 +08:00
"github.com/zu1k/nali/pkg/qqwry"
"github.com/zu1k/nali/pkg/zxipv6wry"
)
func GetDB(typ dbif.QueryType) (db dbif.DB) {
if db, found := dbTypeCache[typ]; found {
2021-08-02 12:01:25 +08:00
return db
}
lang := viper.GetString("selected.lang")
if lang == "" {
lang = "zh-CN"
}
var err error
2021-08-02 12:01:25 +08:00
switch typ {
case dbif.TypeIPv4:
selected := viper.GetString("selected.ipv4")
if selected != "" {
db = getDbByName(selected).get()
break
}
if lang == "zh-CN" {
db, err = qqwry.NewQQwry(getDbByName("qqwry").File)
2021-08-11 10:02:54 +08:00
} else {
db, err = geoip.NewGeoIP(getDbByName("geoip").File)
2021-08-11 10:02:54 +08:00
}
2021-08-02 12:01:25 +08:00
case dbif.TypeIPv6:
selected := viper.GetString("selected.ipv6")
if selected != "" {
db = getDbByName(selected).get()
break
}
if lang == "zh-CN" {
db, err = zxipv6wry.NewZXwry(getDbByName("zxipv6wry").File)
2021-08-11 10:02:54 +08:00
} else {
db, err = geoip.NewGeoIP(getDbByName("geoip").File)
2021-08-11 10:02:54 +08:00
}
2021-08-02 12:01:25 +08:00
case dbif.TypeDomain:
selected := viper.GetString("selected.cdn")
if selected != "" {
db = getDbByName(selected).get()
break
}
db, err = cdn.NewCDN(getDbByName("cdn").File)
2021-08-02 12:01:25 +08:00
default:
panic("Query type not supported!")
}
2021-08-11 10:02:54 +08:00
if err != nil || db == nil {
log.Fatalln("Database init failed:", err)
}
dbTypeCache[typ] = db
2021-08-02 12:01:25 +08:00
return
}
2021-08-11 10:02:54 +08:00
func Find(typ dbif.QueryType, query string) string {
if result, found := queryCache[query]; found {
return result
}
result, err := GetDB(typ).Find(query)
2021-08-11 10:02:54 +08:00
if err != nil {
return ""
}
2021-10-26 13:23:05 +08:00
r := strings.Trim(result.String(), " ")
queryCache[query] = r
return r
2021-08-11 10:02:54 +08:00
}