-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (82 loc) · 1.93 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"log"
"net/http"
"github.com/go-redis/redis"
"encoding/json"
"time"
)
var (
client *redis.Client
config Configuration
numProvider int
)
func main() {
var err error
config, err = GetConfiguration()
if err != nil {
log.Fatal("Configuration read error : " + err.Error())
}
if len(config.Providers) < 1 {
log.Fatal("No ip info providers")
}
client, err = RedisNewClient()
if err != nil {
log.Fatal(err)
}
defer client.Close()
http.HandleFunc("/", handler)
log.Println("server listen 8081")
log.Fatal(http.ListenAndServe(":8081", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
//grab IP from request
ipString, err := GetClientIPHelper(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//check if ip is in DB
ipCountry, err := client.Get(ipString).Result()
if err == redis.Nil {
//key does not exist
//request providers till success or quota limit
for {
numProvider = -1
for i := 0; i < len(config.Providers); i++ {
if checkProvider(i) == nil {
numProvider = i
break
}
}
log.Println("Provider # ", numProvider)
if numProvider == -1 {
http.Error(w, "quota exceeded on all providers", http.StatusInternalServerError)
return
}
//make request to provider
ipCountry, err = getInfo(ipString)
if err == nil {
log.Println("succefully got info from provider")
break
}
}
//save ip to DB
err = client.Set(ipString, ipCountry, time.Duration(config.ExpireTime)*time.Second).Err()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//return result
payload, _ := json.Marshal(struct {
CountryName string
}{ipCountry})
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(payload)
return
}