v / examples / get_weather
Raw file | 55 loc (44 sloc) | 1.29 KB | Latest commit hash 017ace6ea
1import json
2import rand
3import net.http
4
5struct Weather {
6 status string [skip] // drop this field
7 api_version string [skip]
8 api_status string [skip]
9 lang string [skip]
10 unit string [skip]
11 tzshift int [skip]
12 timezone string [skip]
13 server_time u32 [skip]
14 location []f32 [skip]
15 result Result //[json: result] if the field name is different in JSON, it can be specified
16}
17
18struct Result {
19 realtime Realtime [skip]
20 minutely Minutely [skip]
21 hourly Hourly [skip]
22 daily Daily [skip]
23 primary int [skip]
24 forecast_keypoint string
25}
26
27struct Realtime {}
28
29struct Minutely {}
30
31struct Hourly {}
32
33struct Daily {}
34
35fn main() {
36 config := http.FetchConfig{
37 user_agent: 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'
38 }
39
40 rnd := rand.f32()
41 url := 'https://api.caiyunapp.com/v2.5/96Ly7wgKGq6FhllM/116.391912,40.010711/weather.jsonp?hourlysteps=120&random=${rnd}'
42 // println(url)
43
44 resp := http.fetch(http.FetchConfig{ ...config, url: url }) or {
45 println('failed to fetch data from the server')
46 return
47 }
48
49 weather := json.decode(Weather, resp.body) or {
50 println('failed to decode weather json')
51 return
52 }
53
54 println('未来两小时天气:\n${weather.result.forecast_keypoint}.')
55}