diff --git a/src/bunker.go b/src/bunker.go index edb7d30..4a61286 100644 --- a/src/bunker.go +++ b/src/bunker.go @@ -299,6 +299,14 @@ func (e mainEnv) setupRouter() *httprouter.Router { // next step: https://www.sanarias.com/blog/115LearningHTTPcachinginGo w.Header().Set("Cache-Control", "public, max-age=7776000") w.WriteHeader(200) + if strings.HasSuffix(r.URL.Path, ".js") || strings.HasSuffix(r.URL.Path, ".html") { + if bytes.Contains(data, []byte("%IPCOUNTRY%")) { + ipCountry := getCountry(r) + data2 := bytes.ReplaceAll(data, []byte("%IPCOUNTRY%"), []byte(ipCountry)) + w.Write([]byte(data2)) + return + } + } w.Write([]byte(data)) } }) @@ -624,6 +632,7 @@ func main() { db := &dbcon{store, masterKey, hash[:]} e := mainEnv{db, cfg, make(chan struct{})} e.dbCleanup() + initGeoIP() initCaptcha(hash) router := e.setupRouter() router = e.setupConfRouter(router) diff --git a/src/geoip.go b/src/geoip.go new file mode 100644 index 0000000..c24e555 --- /dev/null +++ b/src/geoip.go @@ -0,0 +1,75 @@ +package main + +import ( + "log" + "net" + "net/http" + "strings" + "github.com/gobuffalo/packr" + "github.com/oschwald/geoip2-golang" +) + +var ( + geoipBytes []byte + geoip * geoip2.Reader +) + + +func initGeoIP() { + var err error + box := packr.NewBox("../ui") + geoipBytes, err = box.Find("site/GeoLite2-Country.mmdb") + if err != nil { + log.Fatalf("Failed to load geoip database file") + return + } + geoip, err = geoip2.FromBytes(geoipBytes) + if err != nil { + log.Fatalf("Failed to load geoip database") + return + } + //captchaKey = h +} + +func getCountry(r *http.Request) string { + userIP := "" + //log.Printf("Headers %v", r.Header) + if len(r.Header.Get("CF-Connecting-IP")) > 1 { + userIP = strings.TrimSpace(r.Header.Get("CF-Connecting-IP")) + } + if len(r.Header.Get("X-Forwarded-For")) > 1 && len(userIP) == 0 { + userIP = strings.TrimSpace(r.Header.Get("X-Forwarded-For")) + } + if len(r.Header.Get("X-Real-IP")) > 1 && len(userIP) == 0 { + userIP = strings.TrimSpace(r.Header.Get("X-Real-IP")) + } + if len(userIP) == 0 { + userIP = r.RemoteAddr + } + if strings.Contains(userIP, ",") { + userIP = strings.Split(userIP, ",")[0] + } + if strings.Contains(userIP, " ") { + userIP = strings.Split(userIP, " ")[0] + } + if len(userIP) == 0 { + return "" + } + ip := net.ParseIP(userIP) + if ip == nil { + if strings.Count(userIP, ":") == 1 { + userIP = strings.Split(userIP, ":")[0] + ip = net.ParseIP(userIP) + } + if ip == nil { + log.Printf("Failed to parse userIP: %s", userIP) + return "" + } + } + record, err := geoip.Country(ip) + if err != nil { + log.Printf("Failed to detect country using IP address: %s", userIP) + return "" + } + return record.Country.IsoCode +} diff --git a/ui/site/GeoLite2-Country.mmdb b/ui/site/GeoLite2-Country.mmdb new file mode 100644 index 0000000..578ac8d Binary files /dev/null and b/ui/site/GeoLite2-Country.mmdb differ