v / examples / fetch_ip.v
41 lines · 38 sloc · 837 bytes · c51d30bf5309653c6b573ec815268e69a78ea8cc
Raw
1import json
2import net.http
3
4struct IpInfo {
5 ip string
6 ip_decimal int
7 country string
8 country_iso string
9 country_eu bool
10 region_name string
11 region_code string
12 zip_code string
13 city string
14 latitude f64
15 longitude f64
16 time_zone string
17 asn string
18 asn_org string
19 user_agent UserAgent
20}
21
22struct UserAgent {
23 product string
24 version string
25 comment string
26 raw_value string
27}
28
29url := 'http://ifconfig.co/json'
30resp := http.fetch(
31 url: url
32 user_agent: 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/117.0'
33) or {
34 eprintln('failed to fetch data from the server, error: ${err}')
35 exit(1)
36}
37ip_info := json.decode(IpInfo, resp.body) or {
38 println('failed to decode the json data returned by the server, error: ${err}')
39 exit(2)
40}
41println(ip_info)
42