From 78d1b7f4efcc7969f2fe36e188fba619df7962d8 Mon Sep 17 00:00:00 2001 From: Hunam Date: Sun, 29 May 2022 19:27:18 +0200 Subject: [PATCH] net.http: `Response.text` -> `Response.body` (#14478) --- cmd/tools/vpm.v | 6 +++--- examples/concurrency/concurrency_http.v | 8 +++---- examples/fetch.v | 2 +- examples/get_weather/get_weather.v | 2 +- examples/http_server.v | 2 +- examples/net_t.v | 2 +- examples/news_fetcher.v | 4 ++-- vlib/net/http/download.v | 4 ++-- vlib/net/http/http.v | 2 +- vlib/net/http/http_httpbin_test.v | 8 +++---- vlib/net/http/http_test.v | 12 +++++------ vlib/net/http/response.v | 23 +++++++++++--------- vlib/net/http/response_test.v | 4 ++-- vlib/net/http/server.v | 2 +- vlib/net/http/server_test.v | 6 +++--- vlib/vweb/tests/vweb_test.v | 28 ++++++++++++------------- vlib/vweb/vweb.v | 10 ++++----- vlib/vweb/vweb_app_test.v | 12 ----------- vlib/x/json2/README.md | 2 +- 19 files changed, 65 insertions(+), 74 deletions(-) diff --git a/cmd/tools/vpm.v b/cmd/tools/vpm.v index 6fa5d5a531..b22107f877 100644 --- a/cmd/tools/vpm.v +++ b/cmd/tools/vpm.v @@ -596,7 +596,7 @@ fn get_all_modules() []string { println('Failed to search vpm.vlang.io. Status code: $r.status_code') exit(1) } - s := r.text + s := r.body mut read_len := 0 mut modules := []string{} for read_len < s.len { @@ -733,7 +733,7 @@ fn get_module_meta_info(name string) ?Mod { errors << 'Error details: $err' continue } - if r.status_code == 404 || r.text.trim_space() == '404' { + if r.status_code == 404 || r.body.trim_space() == '404' { errors << 'Skipping module "$name", since "$server_url" reported that "$name" does not exist.' continue } @@ -741,7 +741,7 @@ fn get_module_meta_info(name string) ?Mod { errors << 'Skipping module "$name", since "$server_url" responded with $r.status_code http status code. Please try again later.' continue } - s := r.text + s := r.body if s.len > 0 && s[0] != `{` { errors << 'Invalid json data' errors << s.trim_space().limit(100) + ' ...' diff --git a/examples/concurrency/concurrency_http.v b/examples/concurrency/concurrency_http.v index a62348308e..10b5060f95 100644 --- a/examples/concurrency/concurrency_http.v +++ b/examples/concurrency/concurrency_http.v @@ -7,9 +7,9 @@ fn vlang_time(mut wg sync.WaitGroup) ?string { data := http.get('https://vlang.io/utc_now')? finish := time.ticks() println('Finish getting time ${finish - start} ms') - println(data.text) + println(data.body) wg.done() - return data.text + return data.body } fn remote_ip(mut wg sync.WaitGroup) ?string { @@ -17,9 +17,9 @@ fn remote_ip(mut wg sync.WaitGroup) ?string { data := http.get('https://api.ipify.org')? finish := time.ticks() println('Finish getting ip ${finish - start} ms') - println(data.text) + println(data.body) wg.done() - return data.text + return data.body } fn main() { diff --git a/examples/fetch.v b/examples/fetch.v index 9b804da92e..a218ec0305 100644 --- a/examples/fetch.v +++ b/examples/fetch.v @@ -7,6 +7,6 @@ fn main() { return } - t := time.unix(resp.text.int()) + t := time.unix(resp.body.int()) println(t.format()) } diff --git a/examples/get_weather/get_weather.v b/examples/get_weather/get_weather.v index 4de057207d..e3e5415d27 100644 --- a/examples/get_weather/get_weather.v +++ b/examples/get_weather/get_weather.v @@ -46,7 +46,7 @@ fn main() { return } - weather := json.decode(Weather, resp.text) or { + weather := json.decode(Weather, resp.body) or { println('failed to decode weather json') return } diff --git a/examples/http_server.v b/examples/http_server.v index adeb8fa987..256ccdeb1f 100644 --- a/examples/http_server.v +++ b/examples/http_server.v @@ -11,7 +11,7 @@ fn (h ExampleHandler) handle(req Request) Response { }) } mut status_code := 200 - res.text = match req.url { + res.body = match req.url { '/foo' { 'bar\n' } diff --git a/examples/net_t.v b/examples/net_t.v index 38b9011c10..71fc71acd3 100644 --- a/examples/net_t.v +++ b/examples/net_t.v @@ -8,7 +8,7 @@ fn send_request(mut wg sync.WaitGroup) ?string { finish := time.ticks() println('Finish getting time ${finish - start} ms') wg.done() - return data.text + return data.body } fn main() { diff --git a/examples/news_fetcher.v b/examples/news_fetcher.v index e70941c377..5383a2143c 100644 --- a/examples/news_fetcher.v +++ b/examples/news_fetcher.v @@ -16,7 +16,7 @@ fn worker_fetch(p &pool.PoolProcessor, cursor int, worker_id int) voidptr { println('failed to fetch data from /v0/item/${id}.json') return pool.no_result } - story := json.decode(Story, resp.text) or { + story := json.decode(Story, resp.body) or { println('failed to decode a story') return pool.no_result } @@ -30,7 +30,7 @@ fn main() { println('failed to fetch data from /v0/topstories.json') return } - ids := json.decode([]int, resp.text) or { + ids := json.decode([]int, resp.body) or { println('failed to decode topstories.json') return }#[0..10] diff --git a/vlib/net/http/download.v b/vlib/net/http/download.v index e00137ff05..eab6df8d7e 100644 --- a/vlib/net/http/download.v +++ b/vlib/net/http/download.v @@ -16,9 +16,9 @@ pub fn download_file(url string, out_file_path string) ? { return error('received http code $s.status_code') } $if debug_http ? { - println('http.download_file saving $s.text.len bytes') + println('http.download_file saving $s.body.len bytes') } - os.write_file(out_file_path, s.text)? + os.write_file(out_file_path, s.body)? } // TODO: implement download_file_with_progress diff --git a/vlib/net/http/http.v b/vlib/net/http/http.v index 0641c794ee..1a47709db6 100644 --- a/vlib/net/http/http.v +++ b/vlib/net/http/http.v @@ -161,7 +161,7 @@ pub fn fetch(config FetchConfig) ?Response { // get_text sends a GET HTTP request to the URL and returns the text content of the response pub fn get_text(url string) string { resp := fetch(url: url, method: .get) or { return '' } - return resp.text + return resp.body } // url_encode_form_data converts mapped data to an URL encoded string diff --git a/vlib/net/http/http_httpbin_test.v b/vlib/net/http/http_httpbin_test.v index db35b4682d..458ad31482 100644 --- a/vlib/net/http/http_httpbin_test.v +++ b/vlib/net/http/http_httpbin_test.v @@ -25,7 +25,7 @@ fn http_fetch_mock(_methods []string, _config FetchConfig) ?[]Response { config.method = method_from_str(method) res := fetch(FetchConfig{ ...config, url: url + lmethod })? // TODO - // body := json.decode(HttpbinResponseBody,res.text)? + // body := json.decode(HttpbinResponseBody,res.body)? result << res } return result @@ -49,7 +49,7 @@ fn test_http_fetch_with_data() { data: 'hello world' ) or { panic(err) } for response in responses { - payload := json.decode(HttpbinResponseBody, response.text) or { panic(err) } + payload := json.decode(HttpbinResponseBody, response.body) or { panic(err) } assert payload.data == 'hello world' } } @@ -65,7 +65,7 @@ fn test_http_fetch_with_params() { } ) or { panic(err) } for response in responses { - // payload := json.decode(HttpbinResponseBody,response.text) or { + // payload := json.decode(HttpbinResponseBody,response.body) or { // panic(err) // } assert response.status() == .ok @@ -85,7 +85,7 @@ fn test_http_fetch_with_headers() ? { header: header ) or { panic(err) } for response in responses { - // payload := json.decode(HttpbinResponseBody,response.text) or { + // payload := json.decode(HttpbinResponseBody,response.body) or { // panic(err) // } assert response.status() == .ok diff --git a/vlib/net/http/http_test.v b/vlib/net/http/http_test.v index 8b68073b9f..2ce5d19abf 100644 --- a/vlib/net/http/http_test.v +++ b/vlib/net/http/http_test.v @@ -17,9 +17,9 @@ fn test_http_get_from_vlang_utc_now() { println('Test getting current time from $url by http.get') res := http.get(url) or { panic(err) } assert res.status() == .ok - assert res.text.len > 0 - assert res.text.int() > 1566403696 - println('Current time is: $res.text.int()') + assert res.body.len > 0 + assert res.body.int() > 1566403696 + println('Current time is: $res.body.int()') } } @@ -39,7 +39,7 @@ fn test_public_servers() { println('Testing http.get on public url: $url ') res := http.get(url) or { panic(err) } assert res.status() == .ok - assert res.text.len > 0 + assert res.body.len > 0 } } @@ -51,6 +51,6 @@ fn test_relative_redirects() { } // tempfix periodic: httpbin relative redirects are broken res := http.get('https://httpbin.org/relative-redirect/3?abc=xyz') or { panic(err) } assert res.status() == .ok - assert res.text.len > 0 - assert res.text.contains('"abc": "xyz"') + assert res.body.len > 0 + assert res.body.contains('"abc": "xyz"') } diff --git a/vlib/net/http/response.v b/vlib/net/http/response.v index b1c22f7243..d17bf704cd 100644 --- a/vlib/net/http/response.v +++ b/vlib/net/http/response.v @@ -9,7 +9,8 @@ import strconv // Response represents the result of the request pub struct Response { pub mut: - text string + body string + text string [deprecated: 'use Response.body instead'; deprecated_after: '2022-10-03'] header Header status_code int status_msg string @@ -30,7 +31,7 @@ pub fn (resp Response) bytes() []u8 { pub fn (resp Response) bytestr() string { return 'HTTP/$resp.http_version $resp.status_code $resp.status_msg\r\n' + '${resp.header.render( version: resp.version() - )}\r\n' + '$resp.text' + )}\r\n' + '$resp.body' } // Parse a raw HTTP response into a Response object @@ -39,16 +40,17 @@ pub fn parse_response(resp string) ?Response { // Build resp header map and separate the body start_idx, end_idx := find_headers_range(resp)? header := parse_headers(resp.substr(start_idx, end_idx))? - mut text := resp.substr(end_idx, resp.len) + mut body := resp.substr(end_idx, resp.len) if header.get(.transfer_encoding) or { '' } == 'chunked' { - text = chunked.decode(text) + body = chunked.decode(body) } return Response{ http_version: version status_code: status_code status_msg: status_msg header: header - text: text + body: body + text: body // TODO: remove as depreciated } } @@ -113,18 +115,19 @@ pub struct ResponseConfig { version Version = .v1_1 status Status = .ok header Header - text string + body string + text string [deprecated: 'use ResponseConfig.body instead'; deprecated_after: '2022-10-03'] } // new_response creates a Response object from the configuration. This -// function will add a Content-Length header if text is not empty. +// function will add a Content-Length header if body is not empty. pub fn new_response(conf ResponseConfig) Response { mut resp := Response{ - text: conf.text + body: conf.body + conf.text header: conf.header } - if conf.text.len > 0 && !resp.header.contains(.content_length) { - resp.header.add(.content_length, conf.text.len.str()) + if resp.body.len > 0 && !resp.header.contains(.content_length) { + resp.header.add(.content_length, resp.body.len.str()) } resp.set_status(conf.status) resp.set_version(conf.version) diff --git a/vlib/net/http/response_test.v b/vlib/net/http/response_test.v index a8f45afcdd..f7a27b0c14 100644 --- a/vlib/net/http/response_test.v +++ b/vlib/net/http/response_test.v @@ -4,14 +4,14 @@ fn test_response_bytestr() ? { { resp := new_response( status: .ok - text: 'Foo' + text: 'Foo' // TODO: replace with `body` once deprecaped ) assert resp.bytestr() == 'HTTP/1.1 200 OK\r\n' + 'Content-Length: 3\r\n' + '\r\n' + 'Foo' } { resp := new_response( status: .found - text: 'Foo' + body: 'Foo' header: new_header(key: .location, value: '/') ) lines := resp.bytestr().split_into_lines() diff --git a/vlib/net/http/server.v b/vlib/net/http/server.v index ff3e22f7ff..dbe40909de 100644 --- a/vlib/net/http/server.v +++ b/vlib/net/http/server.v @@ -115,7 +115,7 @@ fn (d DebugHandler) handle(req Request) Response { eprintln('[$time.now()] $req.method $req.url - 200') } mut r := Response{ - text: req.data + body: req.data header: req.header } r.set_status(.ok) diff --git a/vlib/net/http/server_test.v b/vlib/net/http/server_test.v index 0b4e9c85c0..e3af910343 100644 --- a/vlib/net/http/server_test.v +++ b/vlib/net/http/server_test.v @@ -41,7 +41,7 @@ fn (mut handler MyHttpHandler) handle(req http.Request) http.Response { handler.counter++ // eprintln('$time.now() | counter: $handler.counter | $req.method $req.url\n$req.header\n$req.data - 200 OK\n') mut r := http.Response{ - text: req.data + ', $req.url' + body: req.data + ', $req.url' header: req.header } match req.url.all_before('?') { @@ -72,11 +72,11 @@ fn test_server_custom_handler() ? { time.sleep(10 * time.millisecond) } x := http.fetch(url: 'http://localhost:$cport/endpoint?abc=xyz', data: 'my data')? - assert x.text == 'my data, /endpoint?abc=xyz' + assert x.body == 'my data, /endpoint?abc=xyz' assert x.status_code == 200 assert x.http_version == '1.1' y := http.fetch(url: 'http://localhost:$cport/another/endpoint', data: 'abcde')? - assert y.text == 'abcde, /another/endpoint' + assert y.body == 'abcde, /another/endpoint' assert y.status_code == 200 assert y.status() == .ok assert y.http_version == '1.1' diff --git a/vlib/vweb/tests/vweb_test.v b/vlib/vweb/tests/vweb_test.v index b900a006c3..b7e689038d 100644 --- a/vlib/vweb/tests/vweb_test.v +++ b/vlib/vweb/tests/vweb_test.v @@ -120,7 +120,7 @@ fn test_http_client_index() ? { x := http.get('http://$localserver/') or { panic(err) } assert_common_http_headers(x)? assert x.header.get(.content_type)? == 'text/plain' - assert x.text == 'Welcome to VWeb' + assert x.body == 'Welcome to VWeb' } fn test_http_client_404() ? { @@ -139,34 +139,34 @@ fn test_http_client_simple() ? { x := http.get('http://$localserver/simple') or { panic(err) } assert_common_http_headers(x)? assert x.header.get(.content_type)? == 'text/plain' - assert x.text == 'A simple result' + assert x.body == 'A simple result' } fn test_http_client_html_page() ? { x := http.get('http://$localserver/html_page') or { panic(err) } assert_common_http_headers(x)? assert x.header.get(.content_type)? == 'text/html' - assert x.text == '

ok

' + assert x.body == '

ok

' } fn test_http_client_settings_page() ? { x := http.get('http://$localserver/bilbo/settings') or { panic(err) } assert_common_http_headers(x)? - assert x.text == 'username: bilbo' + assert x.body == 'username: bilbo' // y := http.get('http://$localserver/kent/settings') or { panic(err) } assert_common_http_headers(y)? - assert y.text == 'username: kent' + assert y.body == 'username: kent' } fn test_http_client_user_repo_settings_page() ? { x := http.get('http://$localserver/bilbo/gostamp/settings') or { panic(err) } assert_common_http_headers(x)? - assert x.text == 'username: bilbo | repository: gostamp' + assert x.body == 'username: bilbo | repository: gostamp' // y := http.get('http://$localserver/kent/golang/settings') or { panic(err) } assert_common_http_headers(y)? - assert y.text == 'username: kent | repository: golang' + assert y.body == 'username: kent | repository: golang' // z := http.get('http://$localserver/missing/golang/settings') or { panic(err) } assert z.status() == .not_found @@ -188,8 +188,8 @@ fn test_http_client_json_post() ? { eprintln('/json_echo endpoint response: $x') } assert x.header.get(.content_type)? == 'application/json' - assert x.text == json_for_ouser - nuser := json.decode(User, x.text) or { User{} } + assert x.body == json_for_ouser + nuser := json.decode(User, x.body) or { User{} } assert '$ouser' == '$nuser' // x = http.post_json('http://$localserver/json', json_for_ouser) or { panic(err) } @@ -197,8 +197,8 @@ fn test_http_client_json_post() ? { eprintln('/json endpoint response: $x') } assert x.header.get(.content_type)? == 'application/json' - assert x.text == json_for_ouser - nuser2 := json.decode(User, x.text) or { User{} } + assert x.body == json_for_ouser + nuser2 := json.decode(User, x.body) or { User{} } assert '$ouser' == '$nuser2' } @@ -225,7 +225,7 @@ $contents\r $if debug_net_socket_client ? { eprintln('/form_echo endpoint response: $x') } - assert x.text == contents + assert x.body == contents } fn test_http_client_shutdown_does_not_work_without_a_cookie() { @@ -234,7 +234,7 @@ fn test_http_client_shutdown_does_not_work_without_a_cookie() { return } assert x.status() == .not_found - assert x.text == '404 Not Found' + assert x.body == '404 Not Found' } fn testsuite_end() { @@ -251,7 +251,7 @@ fn testsuite_end() { return } assert x.status() == .ok - assert x.text == 'good bye' + assert x.body == 'good bye' } // utility code: diff --git a/vlib/vweb/vweb.v b/vlib/vweb/vweb.v index 630e911751..0fcdbe9a0a 100644 --- a/vlib/vweb/vweb.v +++ b/vlib/vweb/vweb.v @@ -27,12 +27,12 @@ pub const ( http_302 = http.new_response( status: .found - text: '302 Found' + body: '302 Found' header: headers_close ) http_400 = http.new_response( status: .bad_request - text: '400 Bad Request' + body: '400 Bad Request' header: http.new_header( key: .content_type value: 'text/plain' @@ -40,7 +40,7 @@ pub const ( ) http_404 = http.new_response( status: .not_found - text: '404 Not Found' + body: '404 Not Found' header: http.new_header( key: .content_type value: 'text/plain' @@ -48,7 +48,7 @@ pub const ( ) http_500 = http.new_response( status: .internal_server_error - text: '500 Internal Server Error' + body: '500 Internal Server Error' header: http.new_header( key: .content_type value: 'text/plain' @@ -217,7 +217,7 @@ pub fn (mut ctx Context) send_response_to_client(mimetype string, res string) bo mut resp := http.Response{ header: header.join(vweb.headers_close) - text: res + body: res } resp.set_version(.v1_1) resp.set_status(http.status_from_int(ctx.status.int())) diff --git a/vlib/vweb/vweb_app_test.v b/vlib/vweb/vweb_app_test.v index 70e24fa65e..6fa1e987fc 100644 --- a/vlib/vweb/vweb_app_test.v +++ b/vlib/vweb/vweb_app_test.v @@ -25,18 +25,6 @@ fn test_a_vweb_application_compiles() { vweb.run(&App{}, 18081) } -/* -/TODO -pub fn (mut app App) init_server_old() { - app.db = sqlite.connect('blog.db') or { panic(err) } - app.db.create_table('article', [ - 'id integer primary key', - "title text default ''", - "text text default ''", - ]) -} -*/ - pub fn (mut app App) before_request() { app.user_id = app.get_cookie('id') or { '0' } } diff --git a/vlib/x/json2/README.md b/vlib/x/json2/README.md index 75a1cf7e33..af03be0935 100644 --- a/vlib/x/json2/README.md +++ b/vlib/x/json2/README.md @@ -13,7 +13,7 @@ fn main() { resp := http.get('https://example.com')? // raw decode - raw_person := json2.raw_decode(resp.text)? + raw_person := json2.raw_decode(resp.body)? // Casting `Any` type / Navigating person := raw_person.as_map()