-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip.go
51 lines (43 loc) · 928 Bytes
/
ip.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
package iptools
import (
"fmt"
"io"
"net/http"
"net/netip"
"strings"
"github.com/spyzhov/ajson"
)
// GetIP gets your public address from an external service.
func GetIP(url string, jsonpath string) (netip.Addr, error) {
req, err := http.Get(url)
if err != nil {
return netip.Addr{}, err
}
defer req.Body.Close()
body, err := io.ReadAll(req.Body)
if err != nil {
return netip.Addr{}, err
}
// raw format
if jsonpath == "" {
return netip.ParseAddr(strings.TrimRight(string(body), "\n"))
}
// json
root, err := ajson.Unmarshal(body)
if err != nil {
return netip.Addr{}, err
}
nodes, err := root.JSONPath(jsonpath)
if err != nil {
return netip.Addr{}, err
}
if len(nodes) > 0 {
value, err := nodes[0].GetString()
if err != nil {
return netip.Addr{}, err
}
return netip.ParseAddr(value)
}
return netip.Addr{},
fmt.Errorf("There is no IP (%s) in result: %s", jsonpath, body)
}