chore: 优化GeoSite初始化代码

This commit is contained in:
MetaCubeX
2022-06-04 02:58:14 +08:00
parent 8e959bd245
commit c745ea63b2
3 changed files with 9 additions and 58 deletions

View File

@@ -2,19 +2,18 @@ package common
import (
"fmt"
"io"
"net/http"
"os"
"github.com/Dreamacro/clash/component/geodata"
_ "github.com/Dreamacro/clash/component/geodata/memconservative"
"github.com/Dreamacro/clash/component/geodata/router"
_ "github.com/Dreamacro/clash/component/geodata/standard"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/log"
_ "github.com/Dreamacro/clash/component/geodata/memconservative"
_ "github.com/Dreamacro/clash/component/geodata/standard"
_ "unsafe"
)
//go:linkname initGeoSite github.com/Dreamacro/clash/config.initGeoSite
func initGeoSite() error
type GEOSITE struct {
*Base
country string
@@ -80,45 +79,3 @@ func NewGEOSITE(country string, adapter string) (*GEOSITE, error) {
}
var _ C.Rule = (*GEOSITE)(nil)
func downloadGeoSite(path string) (err error) {
resp, err := http.Get(C.GeoSiteUrl)
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
}
func initGeoSite() error {
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
log.Infoln("Can't find GeoSite.dat, start download")
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
}
log.Infoln("Download GeoSite.dat finish")
}
if !initFlag {
err := geodata.Verify(C.GeositeName)
if err != nil {
log.Warnln("GeoSite.dat invalid, remove and download: %s", err)
if err := os.Remove(C.Path.GeoSite()); err != nil {
return fmt.Errorf("can't remove invalid GeoSite.dat: %s", err.Error())
}
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
}
} else {
initFlag = true
}
}
return nil
}