-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
79 lines (71 loc) · 1.5 KB
/
handler.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
79
package main
import (
"encoding/json"
"log"
"net"
"net/http"
"strings"
"github.com/eawsy/aws-lambda-go-core/service/lambda/runtime"
"github.com/futurenda/aws-utils-go/lambda/proxy-integration"
"github.com/oschwald/geoip2-golang"
)
type GeoIP struct {
IP string `json:"ip"`
Data interface{} `json:"data"`
}
func Query(ips []string) ([]*GeoIP, error) {
names := AssetNames()
log.Printf("AssetNames: %v", names)
data, err := Asset("data/GeoLite2-City.mmdb")
if err != nil {
log.Fatal(err)
}
db, err := geoip2.FromBytes(data)
if err != nil {
log.Fatal(err)
}
defer db.Close()
res := []*GeoIP{}
for _, input := range ips {
ip := net.ParseIP(input)
if ip == nil {
continue
}
record, err := db.City(ip)
if err != nil {
return nil, err
}
res = append(res, &GeoIP{
IP: input,
Data: record,
})
}
return res, nil
}
func HandleHTTPRequest(req *http.Request, w http.ResponseWriter) error {
qs := req.URL.Query().Get("ip")
ips := strings.Split(qs, ",")
res, err := Query(ips)
if err != nil {
return err
}
data, err := json.Marshal(res)
if err != nil {
return err
}
w.Header().Add("GeoIP-Service-Version", "v2.0.1")
_, err = w.Write(data)
return err
}
func Handle(event json.RawMessage, ctx *runtime.Context) (interface{}, error) {
req, err := proxyIntegration.NewRequest(event)
if err != nil {
return nil, err
}
w := proxyIntegration.NewResponseWriter()
err = HandleHTTPRequest(req, w)
if err != nil {
return nil, err
}
return w.Response(), nil
}