geoip.go 788 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package main
  2. import (
  3. "net"
  4. "net/http"
  5. "strings"
  6. "github.com/oschwald/geoip2-golang"
  7. )
  8. func getCountryCodeFromRequest(r *http.Request) string {
  9. countryCode := ""
  10. // Get the IP address of the user from the request headers
  11. ipAddress := r.Header.Get("X-Forwarded-For")
  12. if ipAddress == "" {
  13. ipAddress = strings.Split(r.RemoteAddr, ":")[0]
  14. }
  15. // Open the GeoIP database
  16. db, err := geoip2.Open("./system/GeoIP2-Country.mmdb")
  17. if err != nil {
  18. // Handle the error
  19. return countryCode
  20. }
  21. defer db.Close()
  22. // Look up the country code for the IP address
  23. record, err := db.Country(net.ParseIP(ipAddress))
  24. if err != nil {
  25. // Handle the error
  26. return countryCode
  27. }
  28. // Get the ISO country code from the record
  29. countryCode = record.Country.IsoCode
  30. return countryCode
  31. }