Clash.Meta/config/initial.go

55 lines
1.2 KiB
Go
Raw Normal View History

package config
import (
2018-11-21 13:47:46 +08:00
"fmt"
"io"
"net/http"
"os"
C "github.com/Dreamacro/clash/constant"
2019-12-20 17:22:24 +08:00
"github.com/Dreamacro/clash/log"
)
func downloadMMDB(path string) (err error) {
2019-12-31 12:30:42 +08:00
resp, err := http.Get("https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb")
if err != nil {
return
}
defer resp.Body.Close()
2019-12-31 12:30:42 +08:00
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
2019-12-31 12:30:42 +08:00
return err
}
2019-12-31 12:30:42 +08:00
defer f.Close()
_, err = io.Copy(f, resp.Body)
2019-12-31 12:30:42 +08:00
return err
}
// Init prepare necessary files
2018-11-21 13:47:46 +08:00
func Init(dir string) error {
2018-10-14 21:22:58 +08:00
// initial homedir
2018-11-21 13:47:46 +08:00
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0777); err != nil {
return fmt.Errorf("Can't create config directory %s: %s", dir, err.Error())
2018-10-14 21:22:58 +08:00
}
}
// initial config.yaml
2018-10-14 21:22:58 +08:00
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
2019-12-20 17:22:24 +08:00
log.Infoln("Can't find config, create an empty file")
2018-10-14 21:22:58 +08:00
os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644)
}
// initial mmdb
2018-10-14 21:22:58 +08:00
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
2019-12-20 17:22:24 +08:00
log.Infoln("Can't find MMDB, start download")
2018-10-14 21:22:58 +08:00
err := downloadMMDB(C.Path.MMDB())
if err != nil {
2018-11-21 13:47:46 +08:00
return fmt.Errorf("Can't download MMDB: %s", err.Error())
}
}
2018-11-21 13:47:46 +08:00
return nil
}