mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
examples: add web_crawler and get_weather (#10084)
This commit is contained in:
23
examples/get_weather/README.md
Normal file
23
examples/get_weather/README.md
Normal file
@ -0,0 +1,23 @@
|
||||
# get_weather
|
||||
get_weather is a very simple web crawler.
|
||||
Its goal is to get a weather forecast from caiyunapp.com.
|
||||
|
||||
# Compile and Run
|
||||
|
||||
Use this to generate an executable and then launch the web crawler.
|
||||
```bash
|
||||
v get_weather.v
|
||||
./get_weather
|
||||
```
|
||||
|
||||
As a convenience, you can also compile and launch the web crawler directly.
|
||||
```bash
|
||||
v run get_weather.v
|
||||
```
|
||||
|
||||
In this project we use http.fetch() to get a http.Response, with a
|
||||
custom user-agent and then we use json.decode() to decode the json
|
||||
response to struct.
|
||||
We also use a `[skip]` attribute to skip certain fields in the response,
|
||||
that we don't need and use a `[json: result]` attribute to specify that
|
||||
our struct field is named differently from the incoming json response.
|
55
examples/get_weather/get_weather.v
Normal file
55
examples/get_weather/get_weather.v
Normal file
@ -0,0 +1,55 @@
|
||||
import json
|
||||
import rand
|
||||
import net.http
|
||||
|
||||
struct Weather {
|
||||
status string [skip] // drop this field
|
||||
api_version string [skip]
|
||||
api_status string [skip]
|
||||
lang string [skip]
|
||||
unit string [skip]
|
||||
tzshift int [skip]
|
||||
timezone string [skip]
|
||||
server_time u32 [skip]
|
||||
location []f32 [skip]
|
||||
result Result //[json: result] if the field name is different in JSON, it can be specified
|
||||
}
|
||||
|
||||
struct Result {
|
||||
realtime Realtime [skip]
|
||||
minutely Minutely [skip]
|
||||
hourly Hourly [skip]
|
||||
daily Daily [skip]
|
||||
primary int [skip]
|
||||
forecast_keypoint string
|
||||
}
|
||||
|
||||
struct Realtime {}
|
||||
|
||||
struct Minutely {}
|
||||
|
||||
struct Hourly {}
|
||||
|
||||
struct Daily {}
|
||||
|
||||
fn main() {
|
||||
config := http.FetchConfig{
|
||||
user_agent: 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'
|
||||
}
|
||||
|
||||
rnd := rand.f32()
|
||||
url := 'https://api.caiyunapp.com/v2.5/96Ly7wgKGq6FhllM/116.391912,40.010711/weather.jsonp?hourlysteps=120&random=$rnd'
|
||||
// println(url)
|
||||
|
||||
resp := http.fetch(url, config) or {
|
||||
println('failed to fetch data from the server')
|
||||
return
|
||||
}
|
||||
|
||||
weather := json.decode(Weather, resp.text) or {
|
||||
println('failed to decode weather json')
|
||||
return
|
||||
}
|
||||
|
||||
println('未来两小时天气:\n${weather.result.forecast_keypoint}.')
|
||||
}
|
Reference in New Issue
Block a user