blocklist.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/netip"
  8. "strings"
  9. )
  10. // FetchBlocklist reads the blocklist over HTTP and returns every non-commented
  11. // line parsed as an IP address in CIDR notation. IPv4 addresses are returned as
  12. // /32, IPv6 addresses as /128.
  13. //
  14. // This function was generated with GLM 4.7.
  15. func FetchBlocklist(url string) ([]string, error) {
  16. resp, err := http.Get(url)
  17. if err != nil {
  18. return nil, err
  19. }
  20. defer resp.Body.Close()
  21. if resp.StatusCode != http.StatusOK {
  22. return nil, fmt.Errorf("HTTP request failed with status: %s", resp.Status)
  23. }
  24. var lines []string
  25. scanner := bufio.NewScanner(resp.Body)
  26. for scanner.Scan() {
  27. line := scanner.Text()
  28. // Skip empty lines and comments (lines starting with #)
  29. if line == "" || strings.HasPrefix(line, "#") {
  30. continue
  31. }
  32. addr, err := netip.ParseAddr(line)
  33. if err != nil {
  34. // Skip lines that aren't valid IP addresses
  35. continue
  36. }
  37. var cidr string
  38. if addr.Is4() {
  39. cidr = fmt.Sprintf("%s/32", addr.String())
  40. } else {
  41. cidr = fmt.Sprintf("%s/128", addr.String())
  42. }
  43. lines = append(lines, cidr)
  44. }
  45. if err := scanner.Err(); err != nil && err != io.EOF {
  46. return nil, err
  47. }
  48. return lines, nil
  49. }