updater.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package geodb
  2. import (
  3. "io"
  4. "log"
  5. "net/http"
  6. "os"
  7. "imuslab.com/zoraxy/mod/utils"
  8. )
  9. const (
  10. ipv4UpdateSource = "https://cdn.jsdelivr.net/npm/@ip-location-db/geo-whois-asn-country/geo-whois-asn-country-ipv4.csv"
  11. ipv6UpdateSource = "https://cdn.jsdelivr.net/npm/@ip-location-db/geo-whois-asn-country/geo-whois-asn-country-ipv6.csv"
  12. )
  13. // DownloadGeoDBUpdate download the latest geodb update
  14. func DownloadGeoDBUpdate(externalGeoDBStoragePath string) {
  15. //Create the storage path if not exist
  16. if !utils.FileExists(externalGeoDBStoragePath) {
  17. os.MkdirAll(externalGeoDBStoragePath, 0755)
  18. }
  19. //Download the update
  20. log.Println("Downloading IPv4 database update...")
  21. err := downloadFile(ipv4UpdateSource, externalGeoDBStoragePath+"/geoipv4.csv")
  22. if err != nil {
  23. log.Println(err)
  24. return
  25. }
  26. log.Println("Downloading IPv6 database update...")
  27. err = downloadFile(ipv6UpdateSource, externalGeoDBStoragePath+"/geoipv6.csv")
  28. if err != nil {
  29. log.Println(err)
  30. return
  31. }
  32. log.Println("GeoDB update stored at: " + externalGeoDBStoragePath)
  33. log.Println("Exiting...")
  34. }
  35. // Utility functions
  36. func downloadFile(url string, savepath string) error {
  37. resp, err := http.Get(url)
  38. if err != nil {
  39. return err
  40. }
  41. defer resp.Body.Close()
  42. fileContent, err := io.ReadAll(resp.Body)
  43. if err != nil {
  44. return err
  45. }
  46. return os.WriteFile(savepath, fileContent, 0644)
  47. }