Skip to content

Commit 554cc24

Browse files
committed
bug: fix error handing adn typo
1 parent e46ad13 commit 554cc24

5 files changed

Lines changed: 62 additions & 46 deletions

File tree

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
# Output of the go coverage tool, specifically when used with LiteIDE
1515
*.out
16-
16+
.idea
1717
# Dependency directories (remove the comment below to include it)
1818
# vendor/
1919

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Define the output directory for the builds
22
OUTPUT_DIR := ./build
3-
version := 1.8.0
3+
version := 1.8.1
44

55
# Define the name of your binary
66
BINARY_NAME := yourip

geolocation/geolocation.go

Lines changed: 41 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"encoding/json"
66
"errors"
77
"fmt"
8+
"io"
9+
"log"
810
"net"
911
"net/http"
1012
"os"
@@ -273,11 +275,17 @@ func New(RefreshPeroidH time.Duration) *IPGeolocation {
273275
}
274276

275277
go func() {
276-
ipGeolocation.Load(filename)
278+
err := ipGeolocation.Load(filename)
279+
if err != nil {
280+
log.Fatal(err)
281+
}
277282

278283
for {
279284
if !ipGeolocation.Ready || ipGeolocation.RefreshTime.Add(time.Hour*RefreshPeroidH).Before(time.Now()) {
280-
ipGeolocation.RefreshData()
285+
err := ipGeolocation.RefreshData()
286+
if err != nil {
287+
fmt.Println("err in ipGeolocation.RefreshData", err)
288+
}
281289
fmt.Println("\nCIDR is READY.")
282290
time.Sleep(time.Hour * RefreshPeroidH)
283291
} else {
@@ -313,30 +321,39 @@ func (geo *IPGeolocation) IsDataFresh() bool {
313321
return time.Since(geo.RefreshTime).Minutes() < 60
314322
}
315323

316-
func (ig *IPGeolocation) RefreshData() error {
324+
func (geo *IPGeolocation) RefreshData() error {
317325
newCIDRListV4 := make(map[string][]*net.IPNet)
318326
newCIDRListV6 := make(map[string][]*net.IPNet)
319327

320328
lenCountriesCodes := len(CountriesCodes)
321329

322-
for indx, code := range CountriesCodes {
323-
ig.downloadCIDRContent("https://raw.githubusercontent.com/onionj/country-ip-blocks-alternative/master/ipv4/"+code+".netset", code, newCIDRListV4)
324-
ig.downloadCIDRContent("https://raw.githubusercontent.com/onionj/country-ip-blocks-alternative/master/ipv6/"+code+".netset", code, newCIDRListV6)
325-
fmt.Println("Down", code, "CIDR", int32((float32(indx+1))/float32(lenCountriesCodes)*100), "% ")
330+
for index, code := range CountriesCodes {
331+
err := geo.downloadCIDRContent("https://raw.githubusercontent.com/onionj/country-ip-blocks-alternative/master/ipv4/"+code+".netset", code, newCIDRListV4)
332+
if err != nil {
333+
return err
334+
}
335+
err = geo.downloadCIDRContent("https://raw.githubusercontent.com/onionj/country-ip-blocks-alternative/master/ipv6/"+code+".netset", code, newCIDRListV6)
336+
if err != nil {
337+
return err
338+
}
339+
fmt.Println("Down", code, "CIDR", int32((float32(index+1))/float32(lenCountriesCodes)*100), "% ")
326340
fmt.Print("\x0D\u001b[1A")
327341
}
328342

329-
ig.Ready = true
330-
ig.RefreshTime = time.Now()
331-
ig.CIDRListV4 = newCIDRListV4
332-
ig.CIDRListV6 = newCIDRListV6
343+
geo.Ready = true
344+
geo.RefreshTime = time.Now()
345+
geo.CIDRListV4 = newCIDRListV4
346+
geo.CIDRListV6 = newCIDRListV6
333347

334-
ig.Save(filename)
348+
err := geo.Save(filename)
349+
if err != nil {
350+
return err
351+
}
335352

336353
return nil
337354
}
338355

339-
func (ig *IPGeolocation) downloadCIDRContent(url string, code string, newCIDRList map[string][]*net.IPNet) error {
356+
func (geo *IPGeolocation) downloadCIDRContent(url string, code string, newCIDRList map[string][]*net.IPNet) error {
340357
response, err := http.Get(url)
341358

342359
if response.StatusCode != 200 {
@@ -345,7 +362,9 @@ func (ig *IPGeolocation) downloadCIDRContent(url string, code string, newCIDRLis
345362
if err != nil {
346363
return fmt.Errorf("failed to download CIDR for country code %s: %w", code, err)
347364
}
348-
defer response.Body.Close()
365+
defer func(Body io.ReadCloser) {
366+
_ = Body.Close()
367+
}(response.Body)
349368

350369
scanner := bufio.NewScanner(response.Body)
351370
for scanner.Scan() {
@@ -357,31 +376,31 @@ func (ig *IPGeolocation) downloadCIDRContent(url string, code string, newCIDRLis
357376
return fmt.Errorf("failed to read CIDR for country code %s: %w", code, err)
358377
}
359378

360-
ig.Ready = true
361-
ig.RefreshTime = time.Now()
379+
geo.Ready = true
380+
geo.RefreshTime = time.Now()
362381
return nil
363382
}
364383

365-
func (ig IPGeolocation) Query(ip net.IP) (string, error) {
384+
func (geo *IPGeolocation) Query(ip net.IP) (string, error) {
366385
if ip.IsPrivate() || ip.IsLoopback() {
367386
return "", errors.New("IP is private")
368387
}
369388

370-
if !ig.Ready {
389+
if !geo.Ready {
371390
return "", errors.New("IPGeolocation is not ready")
372391
}
373392

374393
if ip.To4() != nil {
375-
for country := range ig.CIDRListV4 {
376-
for _, cidr := range ig.CIDRListV4[country] {
394+
for country := range geo.CIDRListV4 {
395+
for _, cidr := range geo.CIDRListV4[country] {
377396
if cidr.Contains(ip) {
378397
return country, nil
379398
}
380399
}
381400
}
382401
} else {
383-
for country := range ig.CIDRListV6 {
384-
for _, cidr := range ig.CIDRListV6[country] {
402+
for country := range geo.CIDRListV6 {
403+
for _, cidr := range geo.CIDRListV6[country] {
385404
if cidr.Contains(ip) {
386405
return country, nil
387406
}

geolocation/geolocation_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,14 @@ func TestQueryIPV4(t *testing.T) {
1414

1515
ipRangeMap[want] = append(ipRangeMap[want], ipNet)
1616

17-
ipGeoloaction := IPGeolocation{
17+
ipGeolocation := IPGeolocation{
1818
CIDRListV4: ipRangeMap,
1919
Ready: true,
2020
}
2121

2222
testCase := net.IPv4(byte(1), byte(1), byte(1), byte(1))
2323

24-
got, err := ipGeoloaction.Query(testCase)
24+
got, err := ipGeolocation.Query(testCase)
2525
if got != want {
2626
t.Errorf("got %q, wanted %q, error: %q", got, want, err.Error())
2727
}

main.go

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import (
1818
"yourip/geolocation"
1919
)
2020

21-
var version string = "" // set it just in Makefile
21+
var version = "" // set it just in Makefile
2222

2323
const RESPONSE string = `HTTP/1.1 200 OK
2424
Content-Length: %d
@@ -27,15 +27,6 @@ Content-Type: %s; charset=utf-8
2727
2828
%s`
2929

30-
type ResponseMode int8
31-
32-
const (
33-
ResponseModeText ResponseMode = iota
34-
ResponseModeHTTPText
35-
ResponseModeHTTPJson
36-
ResponseModeTextAnimation
37-
)
38-
3930
const (
4031
AnimationModeBanner = "1\n"
4132
AnimationModeFlight = "2\n"
@@ -80,11 +71,13 @@ func main() {
8071
os.Exit(1)
8172
}
8273

83-
defer listener.Close()
74+
defer func(listener *net.TCPListener) {
75+
_ = listener.Close()
76+
}(listener)
8477
fmt.Printf("Start a new listener on %s\nversion:%s\n", tcpAddr.String(), version)
8578

8679
for ; workers != 0; workers-- {
87-
fmt.Println("Runing Worker", workers)
80+
fmt.Println("Running Worker", workers)
8881
go Worker(listener)
8982
}
9083

@@ -123,7 +116,7 @@ func handleConnection(conn net.Conn) {
123116
}
124117
}()
125118

126-
requestBuffer := make([]byte, 1024)
119+
requestBuffer := make([]byte, 2048)
127120
bytesRead, err := conn.Read(requestBuffer)
128121
if err != nil {
129122
if err == io.EOF {
@@ -144,19 +137,22 @@ func handleConnection(conn net.Conn) {
144137

145138
// for netcat client:
146139
if bytesRead <= 1 {
147-
conn.Write([]byte(fmt.Sprintf("%s %s", remoteAddrStr, country)))
140+
fmt.Printf("(%s) return tcp text response to %s (%s)\n", time.Now().String()[:23], remoteAddrStr, country)
141+
_, _ = conn.Write([]byte(fmt.Sprintf("%s %s", remoteAddrStr, country)))
148142
return
149143
}
150144

151145
request := string(requestBuffer[:bytesRead])
152146

153147
if strings.Contains(request, " /json") {
148+
fmt.Printf("(%s) return json response to %s (%s)\n", time.Now().String()[:23], remoteAddrStr, country)
149+
154150
jsonResponseByte, err := json.Marshal(JsonResponse{IP: remoteAddrStr, Country: country})
155151
if err != nil {
156152
fmt.Println("create json response err:", err)
157153
return
158154
}
159-
conn.Write([]byte(fmt.Sprintf(RESPONSE, len(jsonResponseByte), "application/json", jsonResponseByte)))
155+
_, _ = conn.Write([]byte(fmt.Sprintf(RESPONSE, len(jsonResponseByte), "application/json", jsonResponseByte)))
160156
return
161157

162158
} else {
@@ -167,15 +163,16 @@ func handleConnection(conn net.Conn) {
167163
return
168164
}
169165

170-
conn.Write([]byte(fmt.Sprintf(RESPONSE, len(ipWithCountry), "text/plain", ipWithCountry)))
166+
fmt.Printf("(%s) return http text/plain response to %s (%s)\n", time.Now().String()[:23], remoteAddrStr, country)
167+
_, _ = conn.Write([]byte(fmt.Sprintf(RESPONSE, len(ipWithCountry), "text/plain", ipWithCountry)))
171168
}
172169
}
173170

174-
// Stream Client IP Like an Animation (for example client open a tcp connection with netcat and send `1`)
171+
// StreamAnimation : Stream Client IP Like an Animation (for example client open a tcp connection with netcat and send `1`)
175172
func StreamAnimation(conn net.Conn, response string, animationMode string) {
176173
switch animationMode {
177174
case AnimationModeBanner:
178-
fmt.Printf("(%s) Stream animation to %s (Banner)\n", time.Now().String()[:23], conn.RemoteAddr().String())
175+
fmt.Printf("(%s) Stream animation to %s (Banner)\n", time.Now().String()[:23], response)
179176

180177
faces := []string{"(^_^)", "[o_o]", "(^.^)", "(\".\")", "($.$)"}
181178
randomIndex := rand.Intn(len(faces))
@@ -221,8 +218,8 @@ func StreamAnimation(conn net.Conn, response string, animationMode string) {
221218
time.Sleep(time.Second / 5)
222219

223220
// shift string
224-
for indx, lineFlight := range arrayFlight {
225-
arrayFlight[indx] = lineFlight[len(lineFlight)-1:] + lineFlight[:len(lineFlight)-1]
221+
for index, lineFlight := range arrayFlight {
222+
arrayFlight[index] = lineFlight[len(lineFlight)-1:] + lineFlight[:len(lineFlight)-1]
226223
}
227224

228225
}

0 commit comments

Comments
 (0)