From 1f613a082a3af557f78fdb8541fa7370d641afd3 Mon Sep 17 00:00:00 2001 From: Casper Kuethe <43839798+Casper64@users.noreply.github.com> Date: Tue, 28 Mar 2023 22:27:01 +0200 Subject: [PATCH] vweb: use net.http.Cookie (#17807) --- vlib/vweb/vweb.v | 40 +++++++++++++++------------------------- 1 file changed, 15 insertions(+), 25 deletions(-) diff --git a/vlib/vweb/vweb.v b/vlib/vweb/vweb.v index c695c746e7..a8bde7281e 100644 --- a/vlib/vweb/vweb.v +++ b/vlib/vweb/vweb.v @@ -316,15 +316,12 @@ pub fn (mut ctx Context) not_found() Result { // TODO - test // Sets a cookie pub fn (mut ctx Context) set_cookie(cookie http.Cookie) { - mut cookie_data := []string{} - mut secure := if cookie.secure { 'Secure;' } else { '' } - secure += if cookie.http_only { ' HttpOnly' } else { ' ' } - cookie_data << secure - if cookie.expires.unix > 0 { - cookie_data << 'expires=${cookie.expires.utc_string()}' + cookie_raw := cookie.str() + if cookie_raw == '' { + eprintln('error setting cookie: name of cookie is invalid') + return } - data := cookie_data.join(' ') - ctx.add_header('Set-Cookie', '${cookie.name}=${cookie.value}; ${data}') + ctx.add_header('Set-Cookie', cookie_raw) } // Sets the response content type @@ -333,27 +330,20 @@ pub fn (mut ctx Context) set_content_type(typ string) { } // TODO - test -// Sets a cookie with a `expire_data` +// Sets a cookie with a `expire_date` pub fn (mut ctx Context) set_cookie_with_expire_date(key string, val string, expire_date time.Time) { - ctx.add_header('Set-Cookie', '${key}=${val}; Secure; HttpOnly; expires=${expire_date.utc_string()}') + cookie := http.Cookie{ + name: key + value: val + expires: expire_date + } + ctx.set_cookie(cookie) } // Gets a cookie by a key -pub fn (ctx &Context) get_cookie(key string) !string { // TODO refactor - mut cookie_header := ctx.get_header('cookie') - if cookie_header == '' { - cookie_header = ctx.get_header('Cookie') - } - cookie_header = ' ' + cookie_header - // println('cookie_header="$cookie_header"') - // println(ctx.req.header) - cookie := if cookie_header.contains(';') { - cookie_header.find_between(' ${key}=', ';') - } else { - cookie_header.find_between(' ${key}=', '\r') - } - if cookie != '' { - return cookie.trim_space() +pub fn (ctx &Context) get_cookie(key string) !string { + if value := ctx.req.cookies[key] { + return value } return error('Cookie not found') }