v / examples / get_weather / get_weather.v
68 lines · 57 sloc · 1.9 KB · f94fa74a957971b7fd0a2bcd452ff6453c283f39
Raw
1import net.http
2import os
3import rand
4import x.json2 as json
5
6struct Weather {
7 lang string
8 result Result
9}
10
11struct Result {
12 forecast_keypoint string
13}
14
15const config = http.FetchConfig{
16 user_agent: 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'
17}
18
19fn main() {
20 dest_lang := if os.args.len > 1 { os.args[1] } else { 'en' }
21 rnd := rand.f32()
22 url := 'https://api.caiyunapp.com/v2.5/96Ly7wgKGq6FhllM/116.391912,40.010711/weather.jsonp?hourlysteps=120&random=${rnd}'
23
24 resp := http.fetch(http.FetchConfig{ ...config, url: url }) or {
25 println('failed to fetch data from the server')
26 return
27 }
28
29 weather := json.decode[Weather](resp.body) or {
30 println('failed to decode weather json')
31 return
32 }
33
34 for ch in ['未来两小时天气', weather.result.forecast_keypoint] {
35 println('${weather.lang:8}: ${ch}')
36 t := translate(ch, weather.lang, dest_lang) or {
37 println('failed to translate ${ch}: ${err}')
38 continue
39 }
40 println('${dest_lang:8}: ${t}')
41 }
42}
43
44// translate fetch google to print translate text `q` in languate `sl` into language `tl`.
45// A translation typical response json is like: `[[["Weather in the next two hours",
46// "未来两小时天气",null,null,3,null,null,[[null,"offline"]],
47// [[["61549914d65604307a34fd1855292577","offline_launch_doc.md"],null,null,null,null,
48// [[[6,8,0]]]]]]],null,"zh-CN",null,null,null,null,[]]`
49// where translated text is located at position `json_resp[0][0][0]`.
50fn translate(q string, sl string, tl string) !string {
51 url := 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sl}&tl=${tl}&dt=t&q=${q}'
52
53 resp := http.fetch(http.FetchConfig{ ...config, url: url })!
54
55 json_resp := json.decode[json.Any](resp.body)!
56
57 a := json_resp.as_array()
58 if a.len > 0 {
59 a0 := a[0].as_array()
60 if a0.len > 0 {
61 a00 := a0[0].as_array()
62 if a00.len > 0 {
63 return a00[0].str()
64 }
65 }
66 }
67 return error('invalid translation response')
68}
69