Clash.Meta/component/mmdb/mmdb.go

71 lines
1.2 KiB
Go
Raw Normal View History

2022-03-15 01:30:17 +08:00
package mmdb
import (
2023-04-10 21:03:31 +08:00
"context"
2023-01-09 21:07:31 +08:00
"io"
"net/http"
"os"
2022-03-15 01:30:17 +08:00
"sync"
2023-04-10 21:03:31 +08:00
"time"
2022-03-15 01:30:17 +08:00
2023-04-10 21:03:31 +08:00
clashHttp "github.com/Dreamacro/clash/component/http"
2022-03-15 01:30:17 +08:00
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/log"
2023-04-10 21:03:31 +08:00
"github.com/oschwald/geoip2-golang"
2022-03-15 01:30:17 +08:00
)
var (
mmdb *geoip2.Reader
once sync.Once
)
func LoadFromBytes(buffer []byte) {
once.Do(func() {
var err error
mmdb, err = geoip2.FromBytes(buffer)
if err != nil {
log.Fatalln("Can't load mmdb: %s", err.Error())
}
})
}
func Verify() bool {
instance, err := geoip2.Open(C.Path.MMDB())
if err == nil {
instance.Close()
}
return err == nil
}
func Instance() *geoip2.Reader {
once.Do(func() {
var err error
mmdb, err = geoip2.Open(C.Path.MMDB())
if err != nil {
log.Fatalln("Can't load mmdb: %s", err.Error())
}
})
return mmdb
}
2023-01-09 21:07:31 +08:00
func DownloadMMDB(path string) (err error) {
2023-04-10 21:03:31 +08:00
ctx, cancel := context.WithTimeout(context.Background(), time.Second*90)
defer cancel()
resp, err := clashHttp.HttpRequest(ctx, C.MmdbUrl, http.MethodGet, http.Header{"User-Agent": {"clash"}}, nil)
2023-01-09 21:07:31 +08:00
if err != nil {
return
}
defer resp.Body.Close()
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, resp.Body)
return err
}