-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
78 lines (59 loc) · 1.4 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"errors"
"fmt"
"log"
"os"
"strings"
ip2location "github.com/ip2location/ip2location-go"
"github.com/valyala/fasthttp"
)
func main() {
port := os.Getenv("PORT")
log.Printf("starting up [port: %s]\n", port)
h := requestHandler
if err := fasthttp.ListenAndServe(fmt.Sprintf(":%s", port), h); err != nil {
log.Fatalf("Error in ListenAndServe: %s", err)
}
}
func ip6ToCountry(ip string) (string, error) {
db, err := ip2location.OpenDB("./data/IP2LOCATION-LITE-DB1.IPV6.BIN")
if err != nil {
return "", err
}
defer db.Close()
res, err := db.Get_country_short(ip)
if err == nil {
return res.Country_short, nil
}
return "", errors.New("country not found")
}
func ip4ToCountry(ip string) (string, error) {
db, err := ip2location.OpenDB("./data/IP2LOCATION-LITE-DB1.BIN")
if err != nil {
return "", err
}
defer db.Close()
res, err := db.Get_country_short(ip)
if err == nil {
return res.Country_short, nil
}
return "", errors.New("country not found")
}
func requestHandler(ctx *fasthttp.RequestCtx) {
// fmt.Fprintf(ctx, "Requested path is %q\n", ctx.Path())
path := ctx.Path()
country := ""
if len(path) > 1 {
path = path[1 : len(path)-1]
if strings.Count(string(path), ".") == 4 {
country, _ = ip4ToCountry(string(path))
} else {
country, _ = ip6ToCountry(string(path))
}
if len(country) > 2 {
country = ""
}
}
fmt.Fprintf(ctx, country)
}