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

vfmt: change all '$expr' to '${expr}' (#16428)

This commit is contained in:
yuyi
2022-11-15 21:53:13 +08:00
committed by GitHub
parent 56239b4a23
commit 017ace6ea7
859 changed files with 7156 additions and 7135 deletions

View File

@@ -77,7 +77,7 @@ fn (a Ip) str() string {
saddr := unsafe { cstring_to_vstring(&buf[0]) }
port := C.ntohs(a.port)
return '$saddr:$port'
return '${saddr}:${port}'
}
fn (a Ip6) str() string {
@@ -92,7 +92,7 @@ fn (a Ip6) str() string {
saddr := unsafe { cstring_to_vstring(&buf[0]) }
port := C.ntohs(a.port)
return '[$saddr]:$port'
return '[${saddr}]:${port}'
}
const aoffset = __offsetof(Addr, addr)
@@ -187,7 +187,7 @@ pub fn resolve_ipaddrs(addr string, family AddrFamily, typ SocketType) ![]Addr {
results := &C.addrinfo(0)
sport := '$port'
sport := '${port}'
// This might look silly but is recommended by MSDN
$if windows {
@@ -230,7 +230,7 @@ pub fn resolve_ipaddrs(addr string, family AddrFamily, typ SocketType) ![]Addr {
addresses << new_addr
}
else {
panic('Unexpected address family $result.ai_family')
panic('Unexpected address family ${result.ai_family}')
}
}
}

View File

@@ -19,7 +19,7 @@ pub const (
)
pub fn socket_error_message(potential_code int, s string) !int {
return socket_error(potential_code) or { return error('$err.msg(); $s') }
return socket_error(potential_code) or { return error('${err.msg()}; ${s}') }
}
pub fn socket_error(potential_code int) !int {
@@ -27,13 +27,13 @@ pub fn socket_error(potential_code int) !int {
if potential_code < 0 {
last_error_int := C.WSAGetLastError()
last_error := wsa_error(last_error_int)
return error_with_code('net: socket error: ($last_error_int) $last_error',
return error_with_code('net: socket error: (${last_error_int}) ${last_error}',
int(last_error))
}
} $else {
if potential_code < 0 {
last_error := error_code()
return error_with_code('net: socket error: $last_error', last_error)
return error_with_code('net: socket error: ${last_error}', last_error)
}
}
@@ -46,9 +46,9 @@ pub fn wrap_error(error_code int) ! {
}
$if windows {
enum_error := wsa_error(error_code)
return error_with_code('net: socket error: $enum_error', error_code)
return error_with_code('net: socket error: ${enum_error}', error_code)
} $else {
return error_with_code('net: socket error: $error_code', error_code)
return error_with_code('net: socket error: ${error_code}', error_code)
}
}

View File

@@ -77,15 +77,15 @@ pub fn new() FTP {
fn (mut zftp FTP) write(data string) !int {
$if debug {
println('FTP.v >>> $data')
println('FTP.v >>> ${data}')
}
return zftp.conn.write('$data\r\n'.bytes())
return zftp.conn.write('${data}\r\n'.bytes())
}
fn (mut zftp FTP) read() !(int, string) {
mut data := zftp.reader.read_line()!
$if debug {
println('FTP.v <<< $data')
println('FTP.v <<< ${data}')
}
if data.len < 5 {
return 0, ''
@@ -104,7 +104,7 @@ fn (mut zftp FTP) read() !(int, string) {
// connect establishes an FTP connection to the host at `ip` port 21.
pub fn (mut zftp FTP) connect(ip string) !bool {
zftp.conn = net.dial_tcp('$ip:21')!
zftp.conn = net.dial_tcp('${ip}:21')!
zftp.reader = io.new_buffered_reader(reader: zftp.conn)
code, _ := zftp.read()!
if code == ftp.connected {
@@ -115,7 +115,7 @@ pub fn (mut zftp FTP) connect(ip string) !bool {
// login sends the "USER `user`" and "PASS `passwd`" commands to the remote host.
pub fn (mut zftp FTP) login(user string, passwd string) !bool {
zftp.write('USER $user') or {
zftp.write('USER ${user}') or {
$if debug {
println('ERROR sending user')
}
@@ -128,7 +128,7 @@ pub fn (mut zftp FTP) login(user string, passwd string) !bool {
if code != ftp.specify_password {
return false
}
zftp.write('PASS $passwd') or {
zftp.write('PASS ${passwd}') or {
$if debug {
println('ERROR sending password')
}
@@ -160,12 +160,12 @@ pub fn (mut zftp FTP) pwd() !string {
// cd changes the current working directory to the specified remote directory `dir`.
pub fn (mut zftp FTP) cd(dir string) ! {
zftp.write('CWD $dir') or { return }
zftp.write('CWD ${dir}') or { return }
mut code, mut data := zftp.read()!
match int(code) {
ftp.denied {
$if debug {
println('CD $dir denied!')
println('CD ${dir} denied!')
}
}
ftp.complete {
@@ -174,7 +174,7 @@ pub fn (mut zftp FTP) cd(dir string) ! {
else {}
}
$if debug {
println('CD $data')
println('CD ${data}')
}
}
@@ -188,7 +188,7 @@ fn new_dtp(msg string) !&DTP {
port: port
conn: 0
}
conn := net.dial_tcp('$ip:$port') or { return error('Cannot connect to the data channel') }
conn := net.dial_tcp('${ip}:${port}') or { return error('Cannot connect to the data channel') }
dtp.conn = conn
dtp.reader = io.new_buffered_reader(reader: dtp.conn)
return dtp
@@ -198,7 +198,7 @@ fn (mut zftp FTP) pasv() !&DTP {
zftp.write('PASV')!
code, data := zftp.read()!
$if debug {
println('pass: $data')
println('pass: ${data}')
}
if code != ftp.passive_mode {
return error('pasive mode not allowed')
@@ -237,7 +237,7 @@ pub fn (mut zftp FTP) dir() ![]string {
// get retrieves `file` from the remote host.
pub fn (mut zftp FTP) get(file string) ![]u8 {
mut dtp := zftp.pasv() or { return error('Cannot stablish data connection') }
zftp.write('RETR $file')!
zftp.write('RETR ${file}')!
code, _ := zftp.read()!
if code == ftp.denied {
return error('Permission denied')

View File

@@ -141,8 +141,8 @@ fn (mut dom DocumentObjectModel) construct(tag_list []&Tag) {
dom.print_debug("Added ${tag.name} as child of '" + tag_list[temp_int].name +
"' which now has ${dom.btree.get_children().len} childrens")
*/
dom.print_debug("Added $tag.name as child of '" + temp_tag.name +
"' which now has $temp_tag.children.len childrens")
dom.print_debug("Added ${tag.name} as child of '" + temp_tag.name +
"' which now has ${temp_tag.children.len} childrens")
} else { // dom.new_root(tag)
stack.push(root_index)
}

View File

@@ -6,8 +6,8 @@ fn generate_temp_html() string {
mut temp_html := strings.new_builder(200)
temp_html.write_string('<!doctype html><html><head><title>Giant String</title></head><body>')
for counter := 0; counter < 4; counter++ {
temp_html.write_string("<div id='name_$counter' ")
temp_html.write_string("class='several-$counter'>Look at $counter</div>")
temp_html.write_string("<div id='name_${counter}' ")
temp_html.write_string("class='several-${counter}'>Look at ${counter}</div>")
}
temp_html.write_string('</body></html>')
return temp_html.str()

View File

@@ -123,7 +123,7 @@ pub fn (mut parser Parser) split_parse(data string) {
} else if is_quote {
parser.lexical_attributes.open_string = string_code
} else if chr == `>` { // only execute verification if is a > // here will verify < to know if code tag is finished
name_close_tag := '</$parser.lexical_attributes.opened_code_type>'
name_close_tag := '</${parser.lexical_attributes.opened_code_type}>'
if parser.builder_str().to_lower().ends_with(name_close_tag) {
parser.lexical_attributes.open_code = false
// need to modify lexeme_builder to add script text as a content in next loop (not gave error in dom)

View File

@@ -25,7 +25,7 @@ fn test_giant_string() {
mut parser := Parser{}
temp_html.write_string('<!doctype html><html><head><title>Giant String</title></head><body>')
for counter := 0; counter < 2000; counter++ {
temp_html.write_string("<div id='name_$counter' class='several-$counter'>Look at $counter</div>")
temp_html.write_string("<div id='name_${counter}' class='several-${counter}'>Look at ${counter}</div>")
}
temp_html.write_string('</body></html>')
parser.parse_html(temp_html.str())
@@ -35,7 +35,7 @@ fn test_giant_string() {
fn test_script_tag() {
mut parser := Parser{}
script_content := "\nvar googletag = googletag || {};\ngoogletag.cmd = googletag.cmd || [];if(3 > 5) {console.log('Birl');}\n"
temp_html := '<html><body><script>$script_content</script></body></html>'
temp_html := '<html><body><script>${script_content}</script></body></html>'
parser.parse_html(temp_html)
assert parser.tags[2].content.len == script_content.replace('\n', '').len
}

View File

@@ -47,11 +47,11 @@ pub fn (tag Tag) text() string {
pub fn (tag &Tag) str() string {
mut html_str := strings.new_builder(200)
html_str.write_string('<$tag.name')
html_str.write_string('<${tag.name}')
for key, value in tag.attributes {
html_str.write_string(' $key')
html_str.write_string(' ${key}')
if value.len > 0 {
html_str.write_string('="$value"')
html_str.write_string('="${value}"')
}
}
html_str.write_string(if tag.closed && tag.close_type == .in_name { '/>' } else { '>' })
@@ -62,7 +62,7 @@ pub fn (tag &Tag) str() string {
}
}
if !tag.closed || tag.close_type == .new_tag {
html_str.write_string('</$tag.name>')
html_str.write_string('</${tag.name}>')
}
return html_str.str()
}

View File

@@ -18,7 +18,7 @@ fn (req &Request) ssl_do(port int, method Method, host_name string, path string)
req_headers := req.build_request_headers(method, host_name, path)
$if trace_http_request ? {
eprintln('> $req_headers')
eprintln('> ${req_headers}')
}
// println(req_headers)
ssl_conn.write_string(req_headers) or { return err }
@@ -31,7 +31,7 @@ fn (req &Request) ssl_do(port int, method Method, host_name string, path string)
readcounter++
len := ssl_conn.socket_read_into_ptr(bp, bufsize) or { break }
$if debug_http ? {
eprintln('ssl_do, read ${readcounter:4d} | len: $len')
eprintln('ssl_do, read ${readcounter:4d} | len: ${len}')
eprintln('-'.repeat(20))
eprintln(unsafe { tos(bp, len) })
eprintln('-'.repeat(20))
@@ -41,7 +41,7 @@ fn (req &Request) ssl_do(port int, method Method, host_name string, path string)
ssl_conn.shutdown()!
response_text := content.str()
$if trace_http_response ? {
eprintln('< $response_text')
eprintln('< ${response_text}')
}
return parse_response(response_text)
}

View File

@@ -20,13 +20,13 @@ fn (req &Request) ssl_do(port int, method Method, host_name string, path string)
addr := host_name
sdata := req.build_request_headers(method, host_name, path)
$if trace_http_request ? {
eprintln('> $sdata')
eprintln('> ${sdata}')
}
length := C.request(&ctx, port, addr.to_wide(), sdata.str, &buff)
C.vschannel_cleanup(&ctx)
response_text := unsafe { buff.vstring_with_len(length) }
$if trace_http_response ? {
eprintln('< $response_text')
eprintln('< ${response_text}')
}
return parse_response(response_text)
}

View File

@@ -143,7 +143,7 @@ pub fn (c &Cookie) str() string {
}
if c.expires.year > 1600 {
e := c.expires
time_str := '$e.weekday_str(), $e.day.str() $e.smonth() $e.year $e.hhmmss() GMT'
time_str := '${e.weekday_str()}, ${e.day.str()} ${e.smonth()} ${e.year} ${e.hhmmss()} GMT'
b.write_string('; expires=')
b.write_string(time_str)
}
@@ -214,7 +214,7 @@ pub fn sanitize_cookie_value(v string) string {
}
// Check for the existence of a space or comma
if val.starts_with(' ') || val.ends_with(' ') || val.starts_with(',') || val.ends_with(',') {
return '"$v"'
return '"${v}"'
}
return v
}

View File

@@ -9,14 +9,14 @@ import os
// and saves it in the output file path `out_file_path`.
pub fn download_file(url string, out_file_path string) ! {
$if debug_http ? {
println('http.download_file url=$url out_file_path=$out_file_path')
println('http.download_file url=${url} out_file_path=${out_file_path}')
}
s := get(url) or { return err }
if s.status() != .ok {
return error('received http code $s.status_code')
return error('received http code ${s.status_code}')
}
$if debug_http ? {
println('http.download_file saving $s.body.len bytes')
println('http.download_file saving ${s.body.len} bytes')
}
os.write_file(out_file_path, s.body)!
}

View File

@@ -598,7 +598,7 @@ pub fn (h Header) join(other Header) Header {
for v in other.custom_values(k, exact: true) {
combined.add_custom(k, v) or {
// panic because this should never fail
panic('unexpected error: $err')
panic('unexpected error: ${err}')
}
}
}
@@ -634,7 +634,7 @@ struct HeaderKeyError {
}
pub fn (err HeaderKeyError) msg() string {
return "Invalid header key: '$err.header'"
return "Invalid header key: '${err.header}'"
}
pub fn (err HeaderKeyError) code() int {

View File

@@ -374,7 +374,7 @@ fn test_parse_headers() ? {
assert parse_headers('foo: bar\r\nfoo:baz')?.custom_values('foo') == ['bar', 'baz']
if x := parse_headers(' oops: oh no') {
return error('should have errored, but got $x')
return error('should have errored, but got ${x}')
}
}

View File

@@ -93,7 +93,7 @@ pub mut:
pub fn post_multipart_form(url string, conf PostMultipartFormConfig) !Response {
body, boundary := multipart_form_body(conf.form, conf.files)
mut header := conf.header
header.set(.content_type, 'multipart/form-data; boundary="$boundary"')
header.set(.content_type, 'multipart/form-data; boundary="${boundary}"')
return fetch(
method: .post
url: url
@@ -137,7 +137,7 @@ pub fn fetch(config FetchConfig) !Response {
if config.url == '' {
return error('http.fetch: empty url')
}
url := build_url_from_fetch(config) or { return error('http.fetch: invalid url $config.url') }
url := build_url_from_fetch(config) or { return error('http.fetch: invalid url ${config.url}') }
req := Request{
method: config.method
url: url
@@ -170,7 +170,7 @@ pub fn url_encode_form_data(data map[string]string) string {
for key_, value_ in data {
key := urllib.query_escape(key_)
value := urllib.query_escape(value_)
pieces << '$key=$value'
pieces << '${key}=${value}'
}
return pieces.join('&')
}
@@ -189,7 +189,7 @@ fn build_url_from_fetch(config FetchConfig) !string {
}
mut pieces := []string{cap: config.params.len}
for key, val in config.params {
pieces << '$key=$val'
pieces << '${key}=${val}'
}
mut query := pieces.join('&')
if url.raw_query.len > 1 {

View File

@@ -14,12 +14,12 @@ fn test_http_get_from_vlang_utc_now() {
}
urls := ['http://vlang.io/utc_now', 'https://vlang.io/utc_now']
for url in urls {
println('Test getting current time from $url by http.get')
println('Test getting current time from ${url} by http.get')
res := http.get(url) or { panic(err) }
assert res.status() == .ok
assert res.body.len > 0
assert res.body.int() > 1566403696
println('Current time is: $res.body.int()')
println('Current time is: ${res.body.int()}')
}
}
@@ -36,7 +36,7 @@ fn test_public_servers() {
// 'https://yahoo.com/robots.txt',
]
for url in urls {
println('Testing http.get on public url: $url ')
println('Testing http.get on public url: ${url} ')
res := http.get(url) or { panic(err) }
assert res.status() == .ok
assert res.body.len > 0

View File

@@ -25,8 +25,8 @@ fn main() {
// FILE AUTOGENERATED BY `build.vsh` - DO NOT MANUALLY EDIT
const (
db = $mt_map
ext_to_mt_str = $ext_to_mt_str
db = ${mt_map}
ext_to_mt_str = ${ext_to_mt_str}
)
')!
execute('${@VEXE} fmt -w db.v')

View File

@@ -21,7 +21,7 @@ pub fn get_mime_type(ext string) string {
pub fn get_content_type(mt string) string {
mt_struct := db[mt]
charset := if mt_struct.charset.len > 0 { mt_struct.charset.to_lower() } else { 'utf-8' }
return '$mt; charset=$charset'
return '${mt}; charset=${charset}'
}
// returns the default extension for the given MIME type

View File

@@ -54,13 +54,13 @@ pub fn (mut req Request) add_custom_header(key string, val string) ! {
// do will send the HTTP request and returns `http.Response` as soon as the response is recevied
pub fn (req &Request) do() !Response {
mut url := urllib.parse(req.url) or { return error('http.Request.do: invalid url $req.url') }
mut url := urllib.parse(req.url) or { return error('http.Request.do: invalid url ${req.url}') }
mut rurl := url
mut resp := Response{}
mut no_redirects := 0
for {
if no_redirects == max_redirects {
return error('http.request.do: maximum number of redirects reached ($max_redirects)')
return error('http.request.do: maximum number of redirects reached (${max_redirects})')
}
qresp := req.method_and_url_to_response(req.method, rurl)!
resp = qresp
@@ -75,12 +75,12 @@ pub fn (req &Request) do() !Response {
mut redirect_url := resp.header.get(.location) or { '' }
if redirect_url.len > 0 && redirect_url[0] == `/` {
url.set_path(redirect_url) or {
return error('http.request.do: invalid path in redirect: "$redirect_url"')
return error('http.request.do: invalid path in redirect: "${redirect_url}"')
}
redirect_url = url.str()
}
qrurl := urllib.parse(redirect_url) or {
return error('http.request.do: invalid URL in redirect "$redirect_url"')
return error('http.request.do: invalid URL in redirect "${redirect_url}"')
}
rurl = qrurl
no_redirects++
@@ -92,7 +92,7 @@ fn (req &Request) method_and_url_to_response(method Method, url urllib.URL) !Res
host_name := url.hostname()
scheme := url.scheme
p := url.escaped_path().trim_left('/')
path := if url.query().len > 0 { '/$p?$url.query().encode()' } else { '/$p' }
path := if url.query().len > 0 { '/${p}?${url.query().encode()}' } else { '/${p}' }
mut nport := url.port().int()
if nport == 0 {
if scheme == 'http' {
@@ -109,34 +109,35 @@ fn (req &Request) method_and_url_to_response(method Method, url urllib.URL) !Res
return res
} else if scheme == 'http' {
// println('http_do( $nport, $method, $host_name, $path )')
res := req.http_do('$host_name:$nport', method, path)!
res := req.http_do('${host_name}:${nport}', method, path)!
return res
}
return error('http.request.method_and_url_to_response: unsupported scheme: "$scheme"')
return error('http.request.method_and_url_to_response: unsupported scheme: "${scheme}"')
}
fn (req &Request) build_request_headers(method Method, host_name string, path string) string {
ua := req.user_agent
mut uheaders := []string{}
if !req.header.contains(.host) {
uheaders << 'Host: $host_name\r\n'
uheaders << 'Host: ${host_name}\r\n'
}
if !req.header.contains(.user_agent) {
uheaders << 'User-Agent: $ua\r\n'
uheaders << 'User-Agent: ${ua}\r\n'
}
if req.data.len > 0 && !req.header.contains(.content_length) {
uheaders << 'Content-Length: $req.data.len\r\n'
uheaders << 'Content-Length: ${req.data.len}\r\n'
}
for key in req.header.keys() {
if key == CommonHeader.cookie.str() {
continue
}
val := req.header.custom_values(key).join('; ')
uheaders << '$key: $val\r\n'
uheaders << '${key}: ${val}\r\n'
}
uheaders << req.build_request_cookies_header()
version := if req.version == .unknown { Version.v1_1 } else { req.version }
return '$method $path $version\r\n' + uheaders.join('') + 'Connection: close\r\n\r\n' + req.data
return '${method} ${path} ${version}\r\n' + uheaders.join('') + 'Connection: close\r\n\r\n' +
req.data
}
fn (req &Request) build_request_cookies_header() string {
@@ -145,7 +146,7 @@ fn (req &Request) build_request_cookies_header() string {
}
mut cookie := []string{}
for key, val in req.cookies {
cookie << '$key=$val'
cookie << '${key}=${val}'
}
cookie << req.header.values(.cookie)
return 'Cookie: ' + cookie.join('; ') + '\r\n'
@@ -160,13 +161,13 @@ fn (req &Request) http_do(host string, method Method, path string) !Response {
// TODO this really needs to be exposed somehow
client.write(s.bytes())!
$if trace_http_request ? {
eprintln('> $s')
eprintln('> ${s}')
}
mut bytes := io.read_all(reader: client)!
client.close()!
response_text := bytes.bytestr()
$if trace_http_response ? {
eprintln('< $response_text')
eprintln('< ${response_text}')
}
return parse_response(response_text)
}
@@ -286,7 +287,7 @@ pub struct UnexpectedExtraAttributeError {
}
pub fn (err UnexpectedExtraAttributeError) msg() string {
return 'Encountered unexpected extra attributes: $err.attributes'
return 'Encountered unexpected extra attributes: ${err.attributes}'
}
pub struct MultiplePathAttributesError {

View File

@@ -35,7 +35,7 @@ fn test_parse_request_not_http() {
fn test_parse_request_no_headers() {
mut reader_ := reader('GET / HTTP/1.1\r\n\r\n')
req := parse_request(mut reader_) or { panic('did not parse: $err') }
req := parse_request(mut reader_) or { panic('did not parse: ${err}') }
assert req.method == .get
assert req.url == '/'
assert req.version == .v1_1
@@ -43,27 +43,27 @@ fn test_parse_request_no_headers() {
fn test_parse_request_two_headers() {
mut reader_ := reader('GET / HTTP/1.1\r\nTest1: a\r\nTest2: B\r\n\r\n')
req := parse_request(mut reader_) or { panic('did not parse: $err') }
req := parse_request(mut reader_) or { panic('did not parse: ${err}') }
assert req.header.custom_values('Test1') == ['a']
assert req.header.custom_values('Test2') == ['B']
}
fn test_parse_request_two_header_values() {
mut reader_ := reader('GET / HTTP/1.1\r\nTest1: a; b\r\nTest2: c\r\nTest2: d\r\n\r\n')
req := parse_request(mut reader_) or { panic('did not parse: $err') }
req := parse_request(mut reader_) or { panic('did not parse: ${err}') }
assert req.header.custom_values('Test1') == ['a; b']
assert req.header.custom_values('Test2') == ['c', 'd']
}
fn test_parse_request_body() {
mut reader_ := reader('GET / HTTP/1.1\r\nTest1: a\r\nTest2: b\r\nContent-Length: 4\r\n\r\nbodyabc')
req := parse_request(mut reader_) or { panic('did not parse: $err') }
req := parse_request(mut reader_) or { panic('did not parse: ${err}') }
assert req.data == 'body'
}
fn test_parse_request_line() {
method, target, version := parse_request_line('GET /target HTTP/1.1') or {
panic('did not parse: $err')
panic('did not parse: ${err}')
}
assert method == .get
assert target.str() == '/target'
@@ -127,16 +127,16 @@ fn test_parse_multipart_form() {
file := 'bar.v'
ct := 'application/octet-stream'
contents := ['baz', 'buzz']
data := "--$boundary
Content-Disposition: form-data; name=\"${names[0]}\"; filename=\"$file\"\r
Content-Type: $ct\r
data := "--${boundary}
Content-Disposition: form-data; name=\"${names[0]}\"; filename=\"${file}\"\r
Content-Type: ${ct}\r
\r
${contents[0]}\r
--$boundary\r
--${boundary}\r
Content-Disposition: form-data; name=\"${names[1]}\"\r
\r
${contents[1]}\r
--$boundary--\r
--${boundary}--\r
"
form, files := parse_multipart_form(data, boundary)
assert files == {
@@ -176,7 +176,7 @@ fn test_multipart_form_body() {
fn test_parse_large_body() {
body := 'A'.repeat(101) // greater than max_bytes
req := 'GET / HTTP/1.1\r\nContent-Length: $body.len\r\n\r\n$body'
req := 'GET / HTTP/1.1\r\nContent-Length: ${body.len}\r\n\r\n${body}'
mut reader_ := reader(req)
result := parse_request(mut reader_)!
assert result.data.len == body.len

View File

@@ -29,7 +29,7 @@ pub fn (resp Response) bytes() []u8 {
// Formats resp to a string suitable for HTTP response transmission
pub fn (resp Response) bytestr() string {
return 'HTTP/$resp.http_version $resp.status_code $resp.status_msg\r\n' + '${resp.header.render(
return 'HTTP/${resp.http_version} ${resp.status_code} ${resp.status_msg}\r\n' + '${resp.header.render(
version: resp.version()
)}\r\n' + resp.body
}
@@ -98,7 +98,7 @@ pub fn (mut r Response) set_status(s Status) {
// version parses the version
pub fn (r Response) version() Version {
return version_from_str('HTTP/$r.http_version')
return version_from_str('HTTP/${r.http_version}')
}
// set_version sets the http_version string of the response
@@ -108,7 +108,7 @@ pub fn (mut r Response) set_version(v Version) {
return
}
maj, min := v.protos()
r.http_version = '${maj}.$min'
r.http_version = '${maj}.${min}'
}
pub struct ResponseConfig {

View File

@@ -30,7 +30,7 @@ fn check_headers(expected []string, found []string) ! {
assert expected.len == found.len
for header in expected {
if !found.contains(header) {
return error('expected header "$header" not in $found')
return error('expected header "${header}" not in ${found}')
}
}
}

View File

@@ -38,12 +38,12 @@ pub fn (mut s Server) listen_and_serve() {
if s.handler is DebugHandler {
eprintln('Server handler not set, using debug handler')
}
s.listener = net.listen_tcp(.ip6, ':$s.port') or {
eprintln('Listening on :$s.port failed')
s.listener = net.listen_tcp(.ip6, ':${s.port}') or {
eprintln('Listening on :${s.port} failed')
return
}
s.listener.set_accept_timeout(s.accept_timeout)
eprintln('Listening on :$s.port')
eprintln('Listening on :${s.port}')
s.state = .running
for {
// break if we have a stop signal
@@ -55,7 +55,7 @@ pub fn (mut s Server) listen_and_serve() {
// just skip network timeouts, they are normal
continue
}
eprintln('accept() failed, reason: $err; skipping')
eprintln('accept() failed, reason: ${err}; skipping')
continue
}
conn.set_read_timeout(s.read_timeout)
@@ -88,7 +88,7 @@ pub fn (s &Server) status() ServerStatus {
fn (mut s Server) parse_and_respond(mut conn net.TcpConn) {
defer {
conn.close() or { eprintln('close() failed: $err') }
conn.close() or { eprintln('close() failed: ${err}') }
}
mut reader := io.new_buffered_reader(reader: conn)
@@ -100,7 +100,7 @@ fn (mut s Server) parse_and_respond(mut conn net.TcpConn) {
req := parse_request(mut reader) or {
$if debug {
// only show in debug mode to prevent abuse
eprintln('error parsing request: $err')
eprintln('error parsing request: ${err}')
}
return
}
@@ -108,7 +108,7 @@ fn (mut s Server) parse_and_respond(mut conn net.TcpConn) {
if resp.version() == .unknown {
resp.set_version(req.version)
}
conn.write(resp.bytes()) or { eprintln('error sending response: $err') }
conn.write(resp.bytes()) or { eprintln('error sending response: ${err}') }
}
// DebugHandler implements the Handler interface by echoing the request
@@ -117,9 +117,9 @@ struct DebugHandler {}
fn (d DebugHandler) handle(req Request) Response {
$if debug {
eprintln('[$time.now()] $req.method $req.url\n\r$req.header\n\r$req.data - 200 OK')
eprintln('[${time.now()}] ${req.method} ${req.url}\n\r${req.header}\n\r${req.data} - 200 OK')
} $else {
eprintln('[$time.now()] $req.method $req.url - 200')
eprintln('[${time.now()}] ${req.method} ${req.url} - 200')
}
mut r := Response{
body: req.data

View File

@@ -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{
body: req.data + ', $req.url'
body: req.data + ', ${req.url}'
header: req.header
}
match req.url.all_before('?') {
@@ -71,17 +71,17 @@ fn test_server_custom_handler() {
for server.status() != .running {
time.sleep(10 * time.millisecond)
}
x := http.fetch(url: 'http://localhost:$cport/endpoint?abc=xyz', data: 'my data')!
x := http.fetch(url: 'http://localhost:${cport}/endpoint?abc=xyz', data: 'my data')!
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')!
y := http.fetch(url: 'http://localhost:${cport}/another/endpoint', data: 'abcde')!
assert y.body == 'abcde, /another/endpoint'
assert y.status_code == 200
assert y.status() == .ok
assert y.http_version == '1.1'
//
http.fetch(url: 'http://localhost:$cport/something/else')!
http.fetch(url: 'http://localhost:${cport}/something/else')!
server.stop()
t.wait()
assert handler.counter == 3

View File

@@ -16,7 +16,7 @@ fn init() {
0, 0)
if ret != 0 {
C.mbedtls_ctr_drbg_free(&mbedtls.ctr_drbg)
panic('Failed to seed ssl context: $ret')
panic('Failed to seed ssl context: ${ret}')
}
}

View File

@@ -5,10 +5,10 @@ fn ssl_error(ret int, ssl voidptr) !SSLError {
res := C.SSL_get_error(ssl, ret)
match unsafe { SSLError(res) } {
.ssl_error_syscall {
return error_with_code('unrecoverable syscall ($res)', res)
return error_with_code('unrecoverable syscall (${res})', res)
}
.ssl_error_ssl {
return error_with_code('unrecoverable ssl protocol error ($res)', res)
return error_with_code('unrecoverable ssl protocol error (${res})', res)
}
else {
return unsafe { SSLError(res) }

View File

@@ -77,7 +77,7 @@ pub fn (mut s SSLConn) shutdown() ! {
if s.sslctx != 0 {
C.SSL_CTX_free(s.sslctx)
}
return error('unexepedted ssl error $err_res')
return error('unexepedted ssl error ${err_res}')
}
if s.ssl != 0 {
unsafe { C.SSL_free(voidptr(s.ssl)) }
@@ -85,7 +85,7 @@ pub fn (mut s SSLConn) shutdown() ! {
if s.sslctx != 0 {
C.SSL_CTX_free(s.sslctx)
}
return error('Could not connect using SSL. ($err_res),err')
return error('Could not connect using SSL. (${err_res}),err')
} else if res == 0 {
continue
} else if res == 1 {
@@ -155,14 +155,14 @@ fn (mut s SSLConn) init() ! {
if s.config.cert != '' {
res = C.SSL_CTX_use_certificate_file(voidptr(s.sslctx), &char(cert.str), C.SSL_FILETYPE_PEM)
if s.config.validate && res != 1 {
return error('http: openssl: SSL_CTX_use_certificate_file failed, res: $res')
return error('http: openssl: SSL_CTX_use_certificate_file failed, res: ${res}')
}
}
if s.config.cert_key != '' {
res = C.SSL_CTX_use_PrivateKey_file(voidptr(s.sslctx), &char(cert_key.str),
C.SSL_FILETYPE_PEM)
if s.config.validate && res != 1 {
return error('http: openssl: SSL_CTX_use_PrivateKey_file failed, res: $res')
return error('http: openssl: SSL_CTX_use_PrivateKey_file failed, res: ${res}')
}
}
@@ -194,7 +194,7 @@ pub fn (mut s SSLConn) connect(mut tcp_conn net.TcpConn, hostname string) ! {
// dial opens an ssl connection on hostname:port
pub fn (mut s SSLConn) dial(hostname string, port int) ! {
s.owns_socket = true
mut tcp_conn := net.dial_tcp('$hostname:$port') or { return err }
mut tcp_conn := net.dial_tcp('${hostname}:${port}') or { return err }
$if macos {
tcp_conn.set_blocking(true) or { return err }
}
@@ -223,7 +223,7 @@ fn (mut s SSLConn) complete_connect() ! {
}
continue
}
return error('Could not connect using SSL. ($err_res),err')
return error('Could not connect using SSL. (${err_res}),err')
}
break
}
@@ -250,7 +250,7 @@ fn (mut s SSLConn) complete_connect() ! {
}
continue
}
return error('Could not validate SSL certificate. ($err_res),err')
return error('Could not validate SSL certificate. (${err_res}),err')
}
break
}
@@ -294,7 +294,7 @@ pub fn (mut s SSLConn) socket_read_into_ptr(buf_ptr &u8, len int) !int {
return 0
}
else {
return error('Could not read using SSL. ($err_res)')
return error('Could not read using SSL. (${err_res})')
}
}
}
@@ -336,7 +336,7 @@ pub fn (mut s SSLConn) write_ptr(bytes &u8, len int) !int {
} else if err_res == .ssl_error_zero_return {
return error('ssl write on closed connection') // Todo error_with_code close
}
return error_with_code('Could not write SSL. ($err_res),err', int(err_res))
return error_with_code('Could not write SSL. (${err_res}),err', int(err_res))
}
total_sent += sent
}

View File

@@ -77,7 +77,7 @@ pub fn (mut c Client) reconnect() ! {
return error('Already connected to server')
}
conn := net.dial_tcp('$c.server:$c.port') or { return error('Connecting to server failed') }
conn := net.dial_tcp('${c.server}:${c.port}') or { return error('Connecting to server failed') }
c.conn = conn
if c.ssl {
@@ -128,7 +128,7 @@ pub fn (mut c Client) quit() ! {
fn (mut c Client) connect_ssl() ! {
c.ssl_conn = ssl.new_ssl_conn()!
c.ssl_conn.connect(mut c.conn, c.server) or {
return error('Connecting to server using OpenSSL failed: $err')
return error('Connecting to server using OpenSSL failed: ${err}')
}
c.reader = io.new_buffered_reader(reader: c.ssl_conn)
@@ -141,7 +141,7 @@ fn (mut c Client) expect_reply(expected ReplyCode) ! {
for {
str = c.reader.read_line()!
if str.len < 4 {
return error('Invalid SMTP response: $str')
return error('Invalid SMTP response: ${str}')
}
if str.runes()[3] == `-` {
@@ -159,10 +159,10 @@ fn (mut c Client) expect_reply(expected ReplyCode) ! {
if str.len >= 3 {
status := str[..3].int()
if unsafe { ReplyCode(status) } != expected {
return error('Received unexpected status code $status, expecting $expected')
return error('Received unexpected status code ${status}, expecting ${expected}')
}
} else {
return error('Recieved unexpected SMTP data: $str')
return error('Recieved unexpected SMTP data: ${str}')
}
}
@@ -183,7 +183,7 @@ fn (mut c Client) send_str(s string) ! {
[inline]
fn (mut c Client) send_ehlo() ! {
c.send_str('EHLO $c.server\r\n')!
c.send_str('EHLO ${c.server}\r\n')!
c.expect_reply(.action_ok)!
}
@@ -211,13 +211,13 @@ fn (mut c Client) send_auth() ! {
}
fn (mut c Client) send_mailfrom(from string) ! {
c.send_str('MAIL FROM: <$from>\r\n')!
c.send_str('MAIL FROM: <${from}>\r\n')!
c.expect_reply(.action_ok)!
}
fn (mut c Client) send_mailto(to string) ! {
for rcpt in to.split(';') {
c.send_str('RCPT TO: <$rcpt>\r\n')!
c.send_str('RCPT TO: <${rcpt}>\r\n')!
c.expect_reply(.action_ok)!
}
}
@@ -232,16 +232,16 @@ fn (mut c Client) send_body(cfg Mail) ! {
date := cfg.date.custom_format('ddd, D MMM YYYY HH:mm ZZ')
nonascii_subject := cfg.subject.bytes().any(it < u8(` `) || it > u8(`~`))
mut sb := strings.new_builder(200)
sb.write_string('From: $cfg.from\r\n')
sb.write_string('From: ${cfg.from}\r\n')
sb.write_string('To: <${cfg.to.split(';').join('>; <')}>\r\n')
sb.write_string('Cc: <${cfg.cc.split(';').join('>; <')}>\r\n')
sb.write_string('Bcc: <${cfg.bcc.split(';').join('>; <')}>\r\n')
sb.write_string('Date: $date\r\n')
sb.write_string('Date: ${date}\r\n')
if nonascii_subject {
// handle UTF-8 subjects according RFC 1342
sb.write_string('Subject: =?utf-8?B?' + base64.encode_str(cfg.subject) + '?=\r\n')
} else {
sb.write_string('Subject: $cfg.subject\r\n')
sb.write_string('Subject: ${cfg.subject}\r\n')
}
if is_html {

View File

@@ -23,7 +23,7 @@ mut:
pub fn dial_tcp(address string) !&TcpConn {
addrs := resolve_addrs_fuzzy(address, .tcp) or {
return error('$err.msg(); could not resolve address $address in dial_tcp')
return error('${err.msg()}; could not resolve address ${address} in dial_tcp')
}
// Keep track of dialing errors that take place
@@ -32,7 +32,7 @@ pub fn dial_tcp(address string) !&TcpConn {
// Very simple dialer
for addr in addrs {
mut s := new_tcp_socket(addr.family()) or {
return error('$err.msg(); could not create new tcp socket in dial_tcp')
return error('${err.msg()}; could not create new tcp socket in dial_tcp')
}
s.connect(addr) or {
errs << err
@@ -51,12 +51,12 @@ pub fn dial_tcp(address string) !&TcpConn {
// Once we've failed now try and explain why we failed to connect
// to any of these addresses
mut err_builder := strings.new_builder(1024)
err_builder.write_string('dial_tcp failed for address $address\n')
err_builder.write_string('dial_tcp failed for address ${address}\n')
err_builder.write_string('tried addrs:\n')
for i := 0; i < errs.len; i++ {
addr := addrs[i]
why := errs[i]
err_builder.write_string('\t$addr: $why\n')
err_builder.write_string('\t${addr}: ${why}\n')
}
// failed
@@ -66,13 +66,13 @@ pub fn dial_tcp(address string) !&TcpConn {
// bind local address and dial.
pub fn dial_tcp_with_bind(saddr string, laddr string) !&TcpConn {
addrs := resolve_addrs_fuzzy(saddr, .tcp) or {
return error('$err.msg(); could not resolve address $saddr in dial_tcp_with_bind')
return error('${err.msg()}; could not resolve address ${saddr} in dial_tcp_with_bind')
}
// Very simple dialer
for addr in addrs {
mut s := new_tcp_socket(addr.family()) or {
return error('$err.msg(); could not create new tcp socket in dial_tcp_with_bind')
return error('${err.msg()}; could not create new tcp socket in dial_tcp_with_bind')
}
s.bind(laddr) or {
s.close() or { continue }
@@ -91,7 +91,7 @@ pub fn dial_tcp_with_bind(saddr string, laddr string) !&TcpConn {
}
}
// failed
return error('dial_tcp_with_bind failed for address $saddr')
return error('dial_tcp_with_bind failed for address ${saddr}')
}
pub fn (mut c TcpConn) close() ! {
@@ -104,7 +104,7 @@ pub fn (mut c TcpConn) close() ! {
pub fn (c TcpConn) read_ptr(buf_ptr &u8, len int) !int {
mut res := wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0))!
$if trace_tcp ? {
eprintln('<<< TcpConn.read_ptr | c.sock.handle: $c.sock.handle | buf_ptr: ${ptr_str(buf_ptr)} len: $len | res: $res')
eprintln('<<< TcpConn.read_ptr | c.sock.handle: ${c.sock.handle} | buf_ptr: ${ptr_str(buf_ptr)} len: ${len} | res: ${res}')
}
if res > 0 {
$if trace_tcp_data_read ? {
@@ -118,7 +118,7 @@ pub fn (c TcpConn) read_ptr(buf_ptr &u8, len int) !int {
c.wait_for_read()!
res = wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0))!
$if trace_tcp ? {
eprintln('<<< TcpConn.read_ptr | c.sock.handle: $c.sock.handle | buf_ptr: ${ptr_str(buf_ptr)} len: $len | res: $res')
eprintln('<<< TcpConn.read_ptr | c.sock.handle: ${c.sock.handle} | buf_ptr: ${ptr_str(buf_ptr)} len: ${len} | res: ${res}')
}
$if trace_tcp_data_read ? {
if res > 0 {
@@ -153,7 +153,7 @@ pub fn (mut c TcpConn) read_deadline() !time.Time {
pub fn (mut c TcpConn) write_ptr(b &u8, len int) !int {
$if trace_tcp ? {
eprintln(
'>>> TcpConn.write_ptr | c.sock.handle: $c.sock.handle | b: ${ptr_str(b)} len: $len |\n' +
'>>> TcpConn.write_ptr | c.sock.handle: ${c.sock.handle} | b: ${ptr_str(b)} len: ${len} |\n' +
unsafe { b.vstring_with_len(len) })
}
$if trace_tcp_data_write ? {
@@ -257,7 +257,7 @@ pub fn (c &TcpConn) addr() !Addr {
pub fn (c TcpConn) str() string {
s := c.sock.str().replace('\n', ' ').replace(' ', ' ')
return 'TcpConn{ write_deadline: $c.write_deadline, read_deadline: $c.read_deadline, read_timeout: $c.read_timeout, write_timeout: $c.write_timeout, sock: $s }'
return 'TcpConn{ write_deadline: ${c.write_deadline}, read_deadline: ${c.read_deadline}, read_timeout: ${c.read_timeout}, write_timeout: ${c.write_timeout}, sock: ${s} }'
}
pub struct TcpListener {
@@ -269,10 +269,10 @@ mut:
}
pub fn listen_tcp(family AddrFamily, saddr string) !&TcpListener {
s := new_tcp_socket(family) or { return error('$err.msg(); could not create new socket') }
s := new_tcp_socket(family) or { return error('${err.msg()}; could not create new socket') }
addrs := resolve_addrs(saddr, family, .tcp) or {
return error('$err.msg(); could not resolve address $saddr')
return error('${err.msg()}; could not resolve address ${saddr}')
}
// TODO(logic to pick here)
@@ -280,8 +280,8 @@ pub fn listen_tcp(family AddrFamily, saddr string) !&TcpListener {
// cast to the correct type
alen := addr.len()
socket_error_message(C.bind(s.handle, voidptr(&addr), alen), 'binding to $saddr failed')!
socket_error_message(C.listen(s.handle, 128), 'listening on $saddr failed')!
socket_error_message(C.bind(s.handle, voidptr(&addr), alen), 'binding to ${saddr} failed')!
socket_error_message(C.listen(s.handle, 128), 'listening on ${saddr} failed')!
return &TcpListener{
sock: s
accept_deadline: no_deadline
@@ -434,7 +434,7 @@ pub fn (mut s TcpSocket) set_option_int(opt SocketOption, value int) ! {
// bind a local rddress for TcpSocket
pub fn (mut s TcpSocket) bind(addr string) ! {
addrs := resolve_addrs(addr, AddrFamily.ip, .tcp) or {
return error('$err.msg(); could not resolve address $addr')
return error('${err.msg()}; could not resolve address ${addr}')
}
// TODO(logic to pick here)
@@ -442,7 +442,7 @@ pub fn (mut s TcpSocket) bind(addr string) ! {
// cast to the correct type
alen := a.len()
socket_error_message(C.bind(s.handle, voidptr(&a), alen), 'binding to $addr failed') or {
socket_error_message(C.bind(s.handle, voidptr(&a), alen), 'binding to ${addr} failed') or {
return err
}
}

View File

@@ -23,7 +23,7 @@ mut:
}
fn elog(msg string) {
eprintln('$time.now().format_ss_micro() | $msg')
eprintln('${time.now().format_ss_micro()} | ${msg}')
}
fn receive_data(mut con net.TcpConn, shared ctx Context) {
@@ -52,16 +52,16 @@ fn receive_data(mut con net.TcpConn, shared ctx Context) {
fn start_server(schannel chan int, shared ctx Context) {
elog('server: start_server')
mut tcp_listener := net.listen_tcp(net.AddrFamily.ip, ':$xport') or {
elog('server: start server error $err')
mut tcp_listener := net.listen_tcp(net.AddrFamily.ip, ':${xport}') or {
elog('server: start server error ${err}')
return
}
elog('server: server started listening at port :$xport')
elog('server: server started listening at port :${xport}')
schannel <- 0
for {
mut tcp_con := tcp_listener.accept() or {
elog('server: accept error: $err')
elog('server: accept error: ${err}')
lock ctx {
ctx.fail_server_accepts++
}
@@ -71,15 +71,15 @@ fn start_server(schannel chan int, shared ctx Context) {
lock ctx {
ctx.ok_server_accepts++
}
elog('server: new tcp connection con.sock.handle: $tcp_con.sock.handle')
elog('server: new tcp connection con.sock.handle: ${tcp_con.sock.handle}')
continue
}
}
fn start_client(i int, shared ctx Context) {
elog('client [$i]: start')
mut tcp_con := net.dial_tcp('127.0.0.1:$xport') or {
elog('client [$i]: net.dial_tcp err $err')
elog('client [${i}]: start')
mut tcp_con := net.dial_tcp('127.0.0.1:${xport}') or {
elog('client [${i}]: net.dial_tcp err ${err}')
lock ctx {
ctx.fail_client_dials++
}
@@ -88,12 +88,12 @@ fn start_client(i int, shared ctx Context) {
lock ctx {
ctx.ok_client_dials++
}
elog('client [$i]: conn is connected, con.sock.handle: $tcp_con.sock.handle')
tcp_con.write([u8(i)]) or { elog('client [$i]: write failed, err: $err') }
elog('client [${i}]: conn is connected, con.sock.handle: ${tcp_con.sock.handle}')
tcp_con.write([u8(i)]) or { elog('client [${i}]: write failed, err: ${err}') }
time.sleep(1 * time.second)
elog('client [$i]: closing connection...')
elog('client [${i}]: closing connection...')
tcp_con.close() or {
elog('client [$i]: close failed, err: $err')
elog('client [${i}]: close failed, err: ${err}')
lock ctx {
ctx.fail_client_close++
}
@@ -114,7 +114,7 @@ fn test_tcp_self_dialing() {
elog('>>> server was started: ${svalue}. Starting clients:')
for i := int(0); i < 20; i++ {
spawn start_client(i, shared ctx)
elog('>>> started client $i')
elog('>>> started client ${i}')
// time.sleep(2 * time.millisecond)
}
max_dt := 5 * time.second
@@ -122,12 +122,12 @@ fn test_tcp_self_dialing() {
t := time.now()
dt := t - start_time
if dt > max_dt {
elog('>>> exiting after $dt.milliseconds() ms ...')
elog('>>> exiting after ${dt.milliseconds()} ms ...')
lock ctx {
// TODO: fix `dump(ctx)`, when `shared ctx := Type{}`
final_value_for_ctx := ctx // make a value copy as a temporary workaround. TODO: remove when dump(ctx) works.
dump(final_value_for_ctx)
assert ctx.fail_client_dials < 2, 'allowed failed client dials, from $ctx.ok_server_accepts connections'
assert ctx.fail_client_dials < 2, 'allowed failed client dials, from ${ctx.ok_server_accepts} connections'
assert ctx.received.len > ctx.ok_server_accepts / 2, 'at least half the clients sent some data, that was later received by the server'
}
elog('>>> goodbye')

View File

@@ -15,12 +15,12 @@ fn setup() (&net.TcpListener, &net.TcpConn, &net.TcpConn) {
c := chan &net.TcpConn{}
spawn accept(mut server, c)
mut client := net.dial_tcp('localhost$server_port') or { panic(err) }
mut client := net.dial_tcp('localhost${server_port}') or { panic(err) }
socket := <-c
$if debug_peer_ip ? {
eprintln('$server.addr()\n$client.peer_addr(), $client.addr()\n$socket.peer_addr(), $socket.addr()')
eprintln('${server.addr()}\n${client.peer_addr()}, ${client.addr()}\n${socket.peer_addr()}, ${socket.addr()}')
}
assert true
return server, client, socket
@@ -44,10 +44,10 @@ fn test_socket() {
}
assert true
$if debug {
println('message send: $message')
println('message send: ${message}')
}
$if debug {
println('send socket: $socket.sock.handle')
println('send socket: ${socket.sock.handle}')
}
mut buf := []u8{len: 1024}
nbytes := client.read(mut buf) or {
@@ -56,10 +56,10 @@ fn test_socket() {
}
received := buf[0..nbytes].bytestr()
$if debug {
println('message received: $received')
println('message received: ${received}')
}
$if debug {
println('client: $client.sock.handle')
println('client: ${client.sock.handle}')
}
assert message == received
}
@@ -87,7 +87,7 @@ fn test_socket_read_line() {
cleanup(mut server, mut client, mut socket)
}
message1, message2 := 'message1', 'message2'
message := '$message1\n$message2\n'
message := '${message1}\n${message2}\n'
socket.write_string(message) or { assert false }
assert true
//
@@ -124,7 +124,7 @@ fn test_socket_write_fail_without_panic() {
// TODO: fix segfaulting on Solaris and FreeBSD
for i := 0; i < 3; i++ {
socket.write_string(message2) or {
println('write to a socket without a recipient should produce an option fail: $err | $message2')
println('write to a socket without a recipient should produce an option fail: ${err} | ${message2}')
assert true
}
}

View File

@@ -25,7 +25,7 @@ fn one_shot_echo_server(mut l net.TcpListener, ch_started chan int) ? {
eprintln('> one_shot_echo_server')
ch_started <- 1
mut new_conn := l.accept() or { return error('could not accept') }
eprintln(' > new_conn: $new_conn')
eprintln(' > new_conn: ${new_conn}')
handle_conn(mut new_conn)
new_conn.close() or {}
}
@@ -47,13 +47,13 @@ fn echo(address string) ? {
for i := 0; i < read; i++ {
assert buf[i] == data[i]
}
println('Got "$buf.bytestr()"')
println('Got "${buf.bytestr()}"')
}
fn test_tcp_ip6() {
eprintln('\n>>> ${@FN}')
address := 'localhost:$test_port'
mut l := net.listen_tcp(.ip6, ':$test_port') or { panic(err) }
address := 'localhost:${test_port}'
mut l := net.listen_tcp(.ip6, ':${test_port}') or { panic(err) }
dump(l)
start_echo_server(mut l)
echo(address) or { panic(err) }
@@ -70,7 +70,7 @@ fn start_echo_server(mut l net.TcpListener) {
fn test_tcp_ip() {
eprintln('\n>>> ${@FN}')
address := 'localhost:$test_port'
address := 'localhost:${test_port}'
mut l := net.listen_tcp(.ip, address) or { panic(err) }
dump(l)
start_echo_server(mut l)
@@ -86,7 +86,7 @@ fn test_tcp_unix() {
$if !windows {
address := os.real_path('tcp-test.sock')
// address := 'tcp-test.sock'
println('$address')
println('${address}')
mut l := net.listen_tcp(.unix, address) or { panic(err) }
start_echo_server(mut l)

View File

@@ -4,10 +4,10 @@ import time
fn echo_server(mut c net.UdpConn) {
mut count := 0
for {
eprintln('> echo_server loop count: $count')
eprintln('> echo_server loop count: ${count}')
mut buf := []u8{len: 100}
read, addr := c.read(mut buf) or { continue }
eprintln('Server got addr $addr, read: $read | buf: $buf')
eprintln('Server got addr ${addr}, read: ${read} | buf: ${buf}')
c.write_to(addr, buf[..read]) or {
println('Server: connection dropped')
return
@@ -25,19 +25,19 @@ fn echo_server(mut c net.UdpConn) {
const server_addr = '127.0.0.1:40003'
fn echo() ! {
mut c := net.dial_udp(server_addr) or { panic('could not net.dial_udp: $err') }
mut c := net.dial_udp(server_addr) or { panic('could not net.dial_udp: ${err}') }
defer {
c.close() or {}
}
data := 'Hello from vlib/net!'
c.write_string(data) or { panic('could not write_string: $err') }
c.write_string(data) or { panic('could not write_string: ${err}') }
mut buf := []u8{len: 100, init: 0}
read, addr := c.read(mut buf) or { panic('could not read: $err') }
read, addr := c.read(mut buf) or { panic('could not read: ${err}') }
assert read == data.len
println('Got address $addr')
println('Got address ${addr}')
// Can't test this here because loopback addresses
// are mapped to other addresses
// assert addr.str() == '127.0.0.1:30001'
@@ -46,16 +46,16 @@ fn echo() ! {
assert buf[i] == data[i]
}
println('Got "$buf.bytestr()"')
println('Got "${buf.bytestr()}"')
c.close()!
}
fn test_udp() {
mut l := net.listen_udp(server_addr) or { panic('could not listen_udp: $err') }
mut l := net.listen_udp(server_addr) or { panic('could not listen_udp: ${err}') }
spawn echo_server(mut l)
echo() or { panic('could not echo: $err') }
echo() or { panic('could not echo: ${err}') }
l.close() or {}
}

View File

@@ -173,7 +173,7 @@ pub fn (mut c StreamConn) close() ! {
pub fn (mut c StreamConn) write_ptr(b &u8, len int) !int {
$if trace_unix ? {
eprintln(
'>>> StreamConn.write_ptr | c.sock.handle: $c.sock.handle | b: ${ptr_str(b)} len: $len |\n' +
'>>> StreamConn.write_ptr | c.sock.handle: ${c.sock.handle} | b: ${ptr_str(b)} len: ${len} |\n' +
unsafe { b.vstring_with_len(len) })
}
unsafe {
@@ -211,7 +211,7 @@ pub fn (mut c StreamConn) write_string(s string) !int {
pub fn (mut c StreamConn) read_ptr(buf_ptr &u8, len int) !int {
mut res := wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0))!
$if trace_unix ? {
eprintln('<<< StreamConn.read_ptr | c.sock.handle: $c.sock.handle | buf_ptr: ${ptr_str(buf_ptr)} len: $len | res: $res')
eprintln('<<< StreamConn.read_ptr | c.sock.handle: ${c.sock.handle} | buf_ptr: ${ptr_str(buf_ptr)} len: ${len} | res: ${res}')
}
if res > 0 {
return res
@@ -221,7 +221,7 @@ pub fn (mut c StreamConn) read_ptr(buf_ptr &u8, len int) !int {
c.wait_for_read()!
res = wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0))!
$if trace_unix ? {
eprintln('<<< StreamConn.read_ptr | c.sock.handle: $c.sock.handle | buf_ptr: ${ptr_str(buf_ptr)} len: $len | res: $res')
eprintln('<<< StreamConn.read_ptr | c.sock.handle: ${c.sock.handle} | buf_ptr: ${ptr_str(buf_ptr)} len: ${len} | res: ${res}')
}
return net.socket_error(res)
} else {
@@ -284,5 +284,5 @@ pub fn (mut c StreamConn) wait_for_write() ! {
pub fn (c StreamConn) str() string {
s := c.sock.str().replace('\n', ' ').replace(' ', ' ')
return 'StreamConn{ write_deadline: $c.write_deadline, read_deadline: $c.read_deadline, read_timeout: $c.read_timeout, write_timeout: $c.write_timeout, sock: $s }'
return 'StreamConn{ write_deadline: ${c.write_deadline}, read_deadline: ${c.read_deadline}, read_timeout: ${c.read_timeout}, write_timeout: ${c.write_timeout}, sock: ${s} }'
}

View File

@@ -47,7 +47,7 @@ fn echo() ! {
for i := 0; i < read; i++ {
assert buf[i] == data[i]
}
println('Got "$buf.bytestr()"')
println('Got "${buf.bytestr()}"')
return
}

View File

@@ -45,7 +45,7 @@ fn handle_conn(mut c unix.StreamConn) ! {
for {
mut buf := []u8{len: 100, init: 0}
read := c.read(mut buf) or { return perror('Server: connection dropped') }
eprintln('> server read ${read:3}, buf: |$buf.bytestr()|')
eprintln('> server read ${read:3}, buf: |${buf.bytestr()}|')
c.write(buf[..read]) or { return perror('Server: connection dropped') }
}
}

View File

@@ -26,9 +26,9 @@ const (
)
fn error_msg(message string, val string) string {
mut msg := 'net.urllib.$message'
mut msg := 'net.urllib.${message}'
if val != '' {
msg = '$msg ($val)'
msg = '${msg} (${val})'
}
return msg
}
@@ -211,7 +211,7 @@ fn unescape(s_ string, mode EncodingMode) !string {
}
}
if n == 0 && !has_plus {
return '$s' // TODO `return s` once an autofree bug is fixed
return '${s}' // TODO `return s` once an autofree bug is fixed
}
if s.len < 2 * n {
return error(error_msg('unescape: invalid escape sequence', ''))
@@ -331,7 +331,7 @@ pub mut:
// debug returns a string representation of *ALL* the fields of the given URL
pub fn (url &URL) debug() string {
return 'URL{\n scheme: $url.scheme\n opaque: $url.opaque\n user: $url.user\n host: $url.host\n path: $url.path\n raw_path: $url.raw_path\n force_query: $url.force_query\n raw_query: $url.raw_query\n fragment: $url.fragment\n}'
return 'URL{\n scheme: ${url.scheme}\n opaque: ${url.opaque}\n user: ${url.user}\n host: ${url.host}\n path: ${url.path}\n raw_path: ${url.raw_path}\n force_query: ${url.force_query}\n raw_query: ${url.raw_query}\n fragment: ${url.fragment}\n}'
}
// user returns a Userinfo containing the provided username
@@ -584,7 +584,7 @@ fn parse_host(host string) !string {
}
mut colon_port := host[i + 1..]
if !valid_optional_port(colon_port) {
return error(error_msg('parse_host: invalid port $colon_port after host ',
return error(error_msg('parse_host: invalid port ${colon_port} after host ',
''))
}
// RFC 6874 defines that %25 (%-encoded percent) introduces
@@ -602,7 +602,7 @@ fn parse_host(host string) !string {
} else if i := host.last_index(':') {
colon_port := host[i..]
if !valid_optional_port(colon_port) {
return error(error_msg('parse_host: invalid port $colon_port after host ',
return error(error_msg('parse_host: invalid port ${colon_port} after host ',
''))
}
}

View File

@@ -171,10 +171,12 @@ fn (mut ws Client) send_message_event(msg &Message) {
ws.debug_log('sending on_message event')
for ev_handler in ws.message_callbacks {
if !ev_handler.is_ref {
ev_handler.handler(mut ws, msg) or { ws.logger.error('send_message_event error: $err') }
ev_handler.handler(mut ws, msg) or {
ws.logger.error('send_message_event error: ${err}')
}
} else {
ev_handler.handler2(mut ws, msg, ev_handler.ref) or {
ws.logger.error('send_message_event error: $err')
ws.logger.error('send_message_event error: ${err}')
}
}
}
@@ -186,11 +188,11 @@ fn (mut ws Client) send_error_event(error string) {
for ev_handler in ws.error_callbacks {
if !ev_handler.is_ref {
ev_handler.handler(mut ws, error) or {
ws.logger.error('send_error_event error: $error, err: $err')
ws.logger.error('send_error_event error: ${error}, err: ${err}')
}
} else {
ev_handler.handler2(mut ws, error, ev_handler.ref) or {
ws.logger.error('send_error_event error: $error, err: $err')
ws.logger.error('send_error_event error: ${error}, err: ${err}')
}
}
}
@@ -202,11 +204,11 @@ fn (mut ws Client) send_close_event(code int, reason string) {
for ev_handler in ws.close_callbacks {
if !ev_handler.is_ref {
ev_handler.handler(mut ws, code, reason) or {
ws.logger.error('send_close_event error: $err')
ws.logger.error('send_close_event error: ${err}')
}
} else {
ev_handler.handler2(mut ws, code, reason, ev_handler.ref) or {
ws.logger.error('send_close_event error: $err')
ws.logger.error('send_close_event error: ${err}')
}
}
}
@@ -217,10 +219,10 @@ fn (mut ws Client) send_open_event() {
ws.debug_log('sending on_open event')
for ev_handler in ws.open_callbacks {
if !ev_handler.is_ref {
ev_handler.handler(mut ws) or { ws.logger.error('send_open_event error: $err') }
ev_handler.handler(mut ws) or { ws.logger.error('send_open_event error: ${err}') }
} else {
ev_handler.handler2(mut ws, ev_handler.ref) or {
ws.logger.error('send_open_event error: $err')
ws.logger.error('send_open_event error: ${err}')
}
}
}

View File

@@ -25,7 +25,7 @@ fn (mut ws Client) handshake() ! {
sb.write_string('\r\nSec-WebSocket-Version: 13')
for key in ws.header.keys() {
val := ws.header.custom_values(key).join(',')
sb.write_string('\r\n$key:$val')
sb.write_string('\r\n${key}:${val}')
}
sb.write_string('\r\n\r\n')
handshake := sb.str()
@@ -33,7 +33,7 @@ fn (mut ws Client) handshake() ! {
unsafe { handshake.free() }
}
handshake_bytes := handshake.bytes()
ws.debug_log('sending handshake: $handshake')
ws.debug_log('sending handshake: ${handshake}')
ws.socket_write(handshake_bytes)!
ws.read_handshake(seckey)!
unsafe { handshake_bytes.free() }
@@ -49,18 +49,18 @@ fn (mut s Server) handle_server_handshake(mut c Client) !(string, &ServerClient)
// parse_client_handshake parses result from handshake process
fn (mut s Server) parse_client_handshake(client_handshake string, mut c Client) !(string, &ServerClient) {
s.logger.debug('server-> client handshake:\n$client_handshake')
s.logger.debug('server-> client handshake:\n${client_handshake}')
lines := client_handshake.split_into_lines()
get_tokens := lines[0].split(' ')
if get_tokens.len < 3 {
return error_with_code('unexpected get operation, $get_tokens', 1)
return error_with_code('unexpected get operation, ${get_tokens}', 1)
}
if get_tokens[0].trim_space() != 'GET' {
return error_with_code("unexpected request '${get_tokens[0]}', expected 'GET'",
2)
}
if get_tokens[2].trim_space() != 'HTTP/1.1' {
return error_with_code("unexpected request $get_tokens, expected 'HTTP/1.1'",
return error_with_code("unexpected request ${get_tokens}, expected 'HTTP/1.1'",
3)
}
mut seckey := ''
@@ -80,9 +80,9 @@ fn (mut s Server) parse_client_handshake(client_handshake string, mut c Client)
}
'Sec-WebSocket-Key', 'sec-websocket-key' {
key = keys[1].trim_space()
s.logger.debug('server-> got key: $key')
s.logger.debug('server-> got key: ${key}')
seckey = create_key_challenge_response(key)!
s.logger.debug('server-> challenge: $seckey, response: ${keys[1]}')
s.logger.debug('server-> challenge: ${seckey}, response: ${keys[1]}')
flags << .has_accept
}
else {
@@ -92,9 +92,9 @@ fn (mut s Server) parse_client_handshake(client_handshake string, mut c Client)
unsafe { keys.free() }
}
if flags.len < 3 {
return error_with_code('invalid client handshake, $client_handshake', 4)
return error_with_code('invalid client handshake, ${client_handshake}', 4)
}
server_handshake := 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: $seckey\r\n\r\n'
server_handshake := 'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${seckey}\r\n\r\n'
server_client := &ServerClient{
resource_name: get_tokens[1]
client_key: key
@@ -143,11 +143,11 @@ fn (mut ws Client) read_handshake(seckey string) ! {
// check_handshake_response checks the response from handshake and returns
// the response and secure key provided by the websocket client
fn (mut ws Client) check_handshake_response(handshake_response string, seckey string) ! {
ws.debug_log('handshake response:\n$handshake_response')
ws.debug_log('handshake response:\n${handshake_response}')
lines := handshake_response.split_into_lines()
header := lines[0]
if !header.starts_with('HTTP/1.1 101') && !header.starts_with('HTTP/1.0 101') {
return error_with_code('handshake_handler: invalid HTTP status response code, $header',
return error_with_code('handshake_handler: invalid HTTP status response code, ${header}',
6)
}
for i in 1 .. lines.len {
@@ -163,9 +163,9 @@ fn (mut ws Client) check_handshake_response(handshake_response string, seckey st
ws.flags << .has_connection
}
'Sec-WebSocket-Accept', 'sec-websocket-accept' {
ws.debug_log('seckey: $seckey')
ws.debug_log('seckey: ${seckey}')
challenge := create_key_challenge_response(seckey)!
ws.debug_log('challenge: $challenge, response: ${keys[1]}')
ws.debug_log('challenge: ${challenge}, response: ${keys[1]}')
if keys[1].trim_space() != challenge {
return error_with_code('handshake_handler: Sec-WebSocket-Accept header does not match computed sha1/base64 response.',
7)

View File

@@ -72,7 +72,7 @@ fn (mut ws Client) shutdown_socket() ! {
// dial_socket connects tcp socket and initializes default configurations
fn (mut ws Client) dial_socket() !&net.TcpConn {
tcp_address := '$ws.uri.hostname:$ws.uri.port'
tcp_address := '${ws.uri.hostname}:${ws.uri.port}'
mut t := net.dial_tcp(tcp_address)!
optval := int(1)
t.sock.set_option_int(.keep_alive, optval)!

View File

@@ -64,7 +64,7 @@ pub fn (mut ws Client) validate_frame(frame &Frame) ! {
}
}
if frame.fin == false && ws.fragments.len == 0 && frame.opcode == .continuation {
err_msg := 'unexecpected continuation, there are no frames to continue, $frame'
err_msg := 'unexecpected continuation, there are no frames to continue, ${frame}'
ws.close(1002, err_msg)!
return error(err_msg)
}
@@ -111,7 +111,7 @@ fn (mut ws Client) read_payload(frame &Frame) ![]u8 {
// - Future implementation needs to support fail fast utf errors for strict autobahn conformance
fn (mut ws Client) validate_utf_8(opcode OPCode, payload []u8) ! {
if opcode in [.text_frame, .close] && !utf8.validate(payload.data, payload.len) {
ws.logger.error('malformed utf8 payload, payload len: ($payload.len)')
ws.logger.error('malformed utf8 payload, payload len: (${payload.len})')
ws.send_error_event('Recieved malformed utf8.')
ws.close(1007, 'malformed utf8 payload')!
return error('malformed utf8 payload')
@@ -146,8 +146,8 @@ pub fn (mut ws Client) read_next_message() !Message {
}
if ws.fragments.len == 0 {
ws.validate_utf_8(frame.opcode, frame_payload) or {
ws.logger.error('UTF8 validation error: $err, len of payload($frame_payload.len)')
ws.send_error_event('UTF8 validation error: $err, len of payload($frame_payload.len)')
ws.logger.error('UTF8 validation error: ${err}, len of payload(${frame_payload.len})')
ws.send_error_event('UTF8 validation error: ${err}, len of payload(${frame_payload.len})')
return err
}
msg := Message{

View File

@@ -5,8 +5,8 @@ import net.websocket
fn main() {
for i in 1 .. 304 {
println('\ncase: $i')
handle_case(i) or { println('error should be ok: $err') }
println('\ncase: ${i}')
handle_case(i) or { println('error should be ok: ${err}') }
}
// update the reports
uri := 'ws://autobahn_server:9001/updateReports?agent=v-client'
@@ -16,7 +16,7 @@ fn main() {
}
fn handle_case(case_nr int) ! {
uri := 'ws://autobahn_server:9001/runCase?case=$case_nr&agent=v-client'
uri := 'ws://autobahn_server:9001/runCase?case=${case_nr}&agent=v-client'
mut ws := websocket.new_client(uri)!
ws.on_message(on_message)
ws.connect()!

View File

@@ -5,8 +5,8 @@ import net.websocket
fn main() {
for i in 1 .. 304 {
println('\ncase: $i')
handle_case(i) or { println('error should be ok: $err') }
println('\ncase: ${i}')
handle_case(i) or { println('error should be ok: ${err}') }
}
// update the reports
// uri := 'wss://localhost:9002/updateReports?agent=v-client'
@@ -17,7 +17,7 @@ fn main() {
}
fn handle_case(case_nr int) ! {
uri := 'wss://autobahn_server_wss:9002/runCase?case=$case_nr&agent=v-client'
uri := 'wss://autobahn_server_wss:9002/runCase?case=${case_nr}&agent=v-client'
// uri := 'wss://localhost:9002/runCase?case=$case_nr&agent=v-client'
mut ws := websocket.new_client(uri)!
ws.on_message(on_message)

View File

@@ -10,7 +10,7 @@ fn main() {
}
fn handle_case(case_nr int) ! {
uri := 'ws://localhost:9002/runCase?case=$case_nr&agent=v-client'
uri := 'ws://localhost:9002/runCase?case=${case_nr}&agent=v-client'
mut ws := websocket.new_client(uri)!
ws.on_message(on_message)
ws.connect()!

View File

@@ -5,8 +5,8 @@ import net.websocket
fn main() {
for i in 1 .. 304 {
println('\ncase: $i')
handle_case(i) or { println('error should be ok: $err') }
println('\ncase: ${i}')
handle_case(i) or { println('error should be ok: ${err}') }
}
// update the reports
uri := 'ws://localhost:9001/updateReports?agent=v-client'
@@ -16,7 +16,7 @@ fn main() {
}
fn handle_case(case_nr int) ! {
uri := 'ws://localhost:9001/runCase?case=$case_nr&agent=v-client'
uri := 'ws://localhost:9001/runCase?case=${case_nr}&agent=v-client'
mut ws := websocket.new_client(uri)!
ws.on_message(on_message)
ws.connect()!

View File

@@ -5,8 +5,8 @@ import net.websocket
fn main() {
for i in 1 .. 304 {
println('\ncase: $i')
handle_case(i) or { println('error should be ok: $err') }
println('\ncase: ${i}')
handle_case(i) or { println('error should be ok: ${err}') }
}
// update the reports
// uri := 'wss://localhost:9002/updateReports?agent=v-client'
@@ -17,7 +17,7 @@ fn main() {
}
fn handle_case(case_nr int) ! {
uri := 'wss://autobahn_server_wss:9002/runCase?case=$case_nr&agent=v-client'
uri := 'wss://autobahn_server_wss:9002/runCase?case=${case_nr}&agent=v-client'
// uri := 'wss://localhost:9002/runCase?case=$case_nr&agent=v-client'
mut ws := websocket.new_client(uri)!
ws.on_message(on_message)

View File

@@ -109,21 +109,21 @@ pub fn new_client(address string, opt ClientOpt) !&Client {
pub fn (mut ws Client) connect() ! {
ws.assert_not_connected()!
ws.set_state(.connecting)
ws.logger.info('connecting to host $ws.uri')
ws.logger.info('connecting to host ${ws.uri}')
ws.conn = ws.dial_socket()!
ws.handshake()!
ws.set_state(.open)
ws.logger.info('successfully connected to host $ws.uri')
ws.logger.info('successfully connected to host ${ws.uri}')
ws.send_open_event()
}
// listen listens and processes incoming messages
pub fn (mut ws Client) listen() ! {
mut log := 'Starting client listener, server($ws.is_server)...'
mut log := 'Starting client listener, server(${ws.is_server})...'
ws.logger.info(log)
unsafe { log.free() }
defer {
ws.logger.info('Quit client listener, server($ws.is_server)...')
ws.logger.info('Quit client listener, server(${ws.is_server})...')
if ws.state == .open {
ws.close(1000, 'closed by client') or {}
}
@@ -133,14 +133,14 @@ pub fn (mut ws Client) listen() ! {
if ws.state in [.closed, .closing] {
return
}
ws.debug_log('failed to read next message: $err')
ws.send_error_event('failed to read next message: $err')
ws.debug_log('failed to read next message: ${err}')
ws.send_error_event('failed to read next message: ${err}')
return err
}
if ws.state in [.closed, .closing] {
return
}
ws.debug_log('got message: $msg.opcode')
ws.debug_log('got message: ${msg.opcode}')
match msg.opcode {
.text_frame {
log = 'read: text'
@@ -157,8 +157,8 @@ pub fn (mut ws Client) listen() ! {
.ping {
ws.debug_log('read: ping, sending pong')
ws.send_control_frame(.pong, 'PONG', msg.payload) or {
ws.logger.error('error in message callback sending PONG: $err')
ws.send_error_event('error in message callback sending PONG: $err')
ws.logger.error('error in message callback sending PONG: ${err}')
ws.send_error_event('error in message callback sending PONG: ${err}')
if ws.panic_on_callback {
panic(err)
}
@@ -190,8 +190,8 @@ pub fn (mut ws Client) listen() ! {
}
code := u16(msg.payload[0]) << 8 | u16(msg.payload[1])
if code in invalid_close_codes {
ws.close(1002, 'invalid close code: $code')!
return error('invalid close code: $code')
ws.close(1002, 'invalid close code: ${code}')!
return error('invalid close code: ${code}')
}
reason := if msg.payload.len > 2 { msg.payload[2..] } else { []u8{} }
if reason.len > 0 {
@@ -199,7 +199,7 @@ pub fn (mut ws Client) listen() ! {
}
if ws.state !in [.closing, .closed] {
// sending close back according to spec
ws.debug_log('close with reason, code: $code, reason: $reason')
ws.debug_log('close with reason, code: ${code}, reason: ${reason}')
r := reason.bytestr()
ws.close(code, r)!
}
@@ -328,10 +328,10 @@ pub fn (mut ws Client) write_string(str string) !int {
// close closes the websocket connection
pub fn (mut ws Client) close(code int, message string) ! {
ws.debug_log('sending close, $code, $message')
ws.debug_log('sending close, ${code}, ${message}')
if ws.state in [.closed, .closing] || ws.conn.sock.handle <= 1 {
ws.debug_log('close: Websocket allready closed ($ws.state), $message, $code handle($ws.conn.sock.handle)')
err_msg := 'Socket allready closed: $code'
ws.debug_log('close: Websocket allready closed (${ws.state}), ${message}, ${code} handle(${ws.conn.sock.handle})')
err_msg := 'Socket allready closed: ${code}'
return error(err_msg)
}
defer {
@@ -360,7 +360,7 @@ pub fn (mut ws Client) close(code int, message string) ! {
// send_control_frame sends a control frame to the server
fn (mut ws Client) send_control_frame(code OPCode, frame_typ string, payload []u8) ! {
ws.debug_log('send control frame $code, frame_type: $frame_typ')
ws.debug_log('send control frame ${code}, frame_type: ${frame_typ}')
if ws.state !in [.open, .closing] && ws.conn.sock.handle > 1 {
return error('socket is not connected')
}
@@ -414,7 +414,7 @@ fn (mut ws Client) send_control_frame(code OPCode, frame_typ string, payload []u
}
}
ws.socket_write(control_frame) or {
return error('send_control_frame: error sending $frame_typ control frame.')
return error('send_control_frame: error sending ${frame_typ} control frame.')
}
}
@@ -474,9 +474,9 @@ fn (mut ws Client) reset_state() ! {
// debug_log handles debug logging output for client and server
fn (mut ws Client) debug_log(text string) {
if ws.is_server {
ws.logger.debug('server-> $text')
ws.logger.debug('server-> ${text}')
} else {
ws.logger.debug('client-> $text')
ws.logger.debug('client-> ${text}')
}
}

View File

@@ -61,15 +61,15 @@ pub fn (mut s Server) set_ping_interval(seconds int) {
// listen start listen and process to incoming connections from websocket clients
pub fn (mut s Server) listen() ! {
s.logger.info('websocket server: start listen on port $s.port')
s.ls = net.listen_tcp(s.family, ':$s.port')!
s.logger.info('websocket server: start listen on port ${s.port}')
s.ls = net.listen_tcp(s.family, ':${s.port}')!
s.set_state(.open)
spawn s.handle_ping()
for {
mut c := s.accept_new_client() or { continue }
spawn s.serve_client(mut c)
}
s.logger.info('websocket server: end listen on port $s.port')
s.logger.info('websocket server: end listen on port ${s.port}')
}
// Close closes server (not implemented yet)
@@ -111,9 +111,9 @@ fn (mut s Server) handle_ping() {
// serve_client accepts incoming connection and sets up the callbacks
fn (mut s Server) serve_client(mut c Client) ! {
c.logger.debug('server-> Start serve client ($c.id)')
c.logger.debug('server-> Start serve client (${c.id})')
defer {
c.logger.debug('server-> End serve client ($c.id)')
c.logger.debug('server-> End serve client (${c.id})')
}
mut handshake_response, mut server_client := s.handle_server_handshake(mut c)!
accept := s.send_connect_event(mut server_client)!

View File

@@ -26,11 +26,11 @@ fn test_ws_ipv6() {
return
}
port := 30000 + rand.intn(1024) or { 0 }
eprintln('> port ipv6: $port')
eprintln('> port ipv6: ${port}')
spawn start_server(.ip6, port)
time.sleep(1500 * time.millisecond)
ws_test(.ip6, 'ws://localhost:$port') or {
eprintln('> error while connecting .ip6, err: $err')
ws_test(.ip6, 'ws://localhost:${port}') or {
eprintln('> error while connecting .ip6, err: ${err}')
assert false
}
}
@@ -41,11 +41,11 @@ fn test_ws_ipv4() {
return
}
port := 30000 + rand.intn(1024) or { 0 }
eprintln('> port ipv4: $port')
eprintln('> port ipv4: ${port}')
spawn start_server(.ip, port)
time.sleep(1500 * time.millisecond)
ws_test(.ip, 'ws://localhost:$port') or {
eprintln('> error while connecting .ip, err: $err')
ws_test(.ip, 'ws://localhost:${port}') or {
eprintln('> error while connecting .ip, err: ${err}')
assert false
}
}
@@ -74,12 +74,12 @@ fn start_server(family net.AddrFamily, listen_port int) ! {
s.on_close(fn (mut ws websocket.Client, code int, reason string) ! {
// not used
})
s.listen() or { panic('websocket server could not listen, err: $err') }
s.listen() or { panic('websocket server could not listen, err: ${err}') }
}
// ws_test tests connect to the websocket server from websocket client
fn ws_test(family net.AddrFamily, uri string) ! {
eprintln('connecting to $uri ...')
eprintln('connecting to ${uri} ...')
mut test_results := WebsocketTestResults{}
mut ws := websocket.new_client(uri)!
@@ -88,13 +88,13 @@ fn ws_test(family net.AddrFamily, uri string) ! {
assert true
})
ws.on_error(fn (mut ws websocket.Client, err string) ! {
println('error: $err')
println('error: ${err}')
// this can be thrown by internet connection problems
assert false
})
ws.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, mut res WebsocketTestResults) ! {
println('client got type: $msg.opcode payload:\n$msg.payload')
println('client got type: ${msg.opcode} payload:\n${msg.payload}')
if msg.opcode == .text_frame {
smessage := msg.payload.bytestr()
match smessage {
@@ -109,14 +109,14 @@ fn ws_test(family net.AddrFamily, uri string) ! {
}
}
} else {
println('Binary message: $msg')
println('Binary message: ${msg}')
}
}, test_results)
ws.connect() or { panic('fail to connect, err: $err') }
ws.connect() or { panic('fail to connect, err: ${err}') }
spawn ws.listen()
text := ['a'].repeat(2)
for msg in text {
ws.write(msg.bytes(), .text_frame) or { panic('fail to write to websocket, err: $err') }
ws.write(msg.bytes(), .text_frame) or { panic('fail to write to websocket, err: ${err}') }
// sleep to give time to recieve response before send a new one
time.sleep(100 * time.millisecond)
}