1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

http: use optionals (finally)

This commit is contained in:
Alexander Medvednikov 2019-07-31 22:10:28 +02:00
parent 15f1169102
commit aac8503d83
4 changed files with 17 additions and 30 deletions

View File

@ -1,14 +1,7 @@
// Copyright (c) 2019 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
import http
fn main() {
html := http.get('https://news.ycombinator.com') or {
println('Failed fetching from URL')
return
}
html := http.get_text('https://news.ycombinator.com')
mut pos := 0
for {
pos = html.index_after('https://', pos + 1)

View File

@ -37,7 +37,7 @@ fn (f mut Fetcher) fetch() {
println('failed to fetch data from /v0/item/${id}.json')
exit(1)
}
story := json.decode(Story, resp) or {
story := json.decode(Story, resp.text) or {
println('failed to decode a story')
exit(1)
}
@ -52,7 +52,7 @@ fn main() {
println('failed to fetch data from /v0/topstories.json')
return
}
mut ids := json.decode([]int, resp) or {
mut ids := json.decode([]int, resp.text) or {
println('failed to decode topstories.json')
return
}

View File

@ -22,47 +22,36 @@ pub:
struct Response {
pub:
body string
headers map_string
text string
headers map[string]string
status_code int
}
// embed 'http'
pub fn fetch(typ, url, data string) ?Response {
pub fn get(url string) ?Response {
req := new_request('GET', url, '') or {
return error(err)
}
resp := req.do()
return resp
return req.do()
}
pub fn get(url string) ?string {
resp := fetch('GET', url, '') or {
pub fn post(url, data string) ?Response {
req := new_request('POST', url, data) or {
return error(err)
}
return resp.body
}
pub fn post(url, data string) ?string {
resp := fetch('POST', url, data) or {
return error(err)
}
return resp.body
return req.do()
}
pub fn new_request(typ, _url, _data string) ?Request {
if _url == '' {
return error('http: empty url')
return error('bad url')
}
mut url := _url
mut data := _data
// req.headers['User-Agent'] = 'V $VERSION'
if typ == 'GET' && !url.contains('?') && data != '' {
println('zeroing data, to url')
url = '$url?$data'
data = ''
}
// req.headers = new_map(0, sizeof(string))// []string{}
return Request {
typ: typ
url: url
@ -73,6 +62,11 @@ pub fn new_request(typ, _url, _data string) ?Request {
}
}
pub fn get_text(url string) string {
resp := get(url) or { return '' }
return resp.text
}
fn (req mut Request) free() {
req.headers.free()
}

View File

@ -185,7 +185,7 @@ pub fn (req &Request) do() Response {
C.curl_easy_cleanup(curl)
//println('end of req.do() url="$req.url"')
return Response {
body: body
text: body
}
}