-
Notifications
You must be signed in to change notification settings - Fork 135
/
endpoints.go
95 lines (77 loc) · 2.12 KB
/
endpoints.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
/*
* Telize 4.0.0
* Copyright (c) 2013-2023, Frederic Cambus
* https://www.telize.com
*
* Created: 2013-08-15
* Last Updated: 2022-11-24
*
* Telize is released under the BSD 2-Clause license.
* See LICENSE file for details.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
package main
import (
"github.com/go-chi/chi/v5"
"io"
"net"
"net/http"
"time"
)
func ip(w http.ResponseWriter, r *http.Request) {
ip := request_ip(r)
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Content-Type", "text/plain")
io.WriteString(w, ip)
}
func jsonip(w http.ResponseWriter, r *http.Request) {
ip := request_ip(r)
jsonip := payload{IP: ip}
jsonify(w, r, &jsonip)
}
func location(w http.ResponseWriter, r *http.Request) {
ip := chi.URLParam(r, "ip")
if ip == "" {
ip = request_ip(r)
}
address := net.ParseIP(ip)
var asn_record ASN
err := asn.Lookup(address, &asn_record)
if err != nil {
errorCode(w, 400, 401, "Input string is not a valid IP address")
return
}
var record City
err = city.Lookup(address, &record)
if err != nil {
errorCode(w, 400, 401, "Input string is not a valid IP address")
return
}
location := payload{
IP: ip,
Continent: record.Continent.Code,
Country: record.Country.Names["en"],
CountryCode: record.Country.IsoCode,
CountryCode3: CountryCode3[record.Country.IsoCode],
IsInEuropeanUnion: record.Country.IsInEuropeanUnion,
City: record.City.Names["en"],
PostalCode: record.Postal.Code,
Latitude: record.Location.Latitude,
Longitude: record.Location.Longitude,
TimeZone: record.Location.TimeZone,
ASN: asn_record.AutonomousSystemNumber,
Organization: asn_record.AutonomousSystemOrganization,
}
if record.Subdivisions != nil {
location.Region = record.Subdivisions[0].Names["en"]
location.RegionCode = record.Subdivisions[0].IsoCode
}
if record.Location.TimeZone != "" {
if tz, err := time.LoadLocation(record.Location.TimeZone); err == nil {
_, offset := time.Now().In(tz).Zone()
location.Offset = &offset
}
}
jsonify(w, r, &location)
}