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

vweb: use net.http.Cookie (#17807)

This commit is contained in:
Casper Kuethe 2023-03-28 22:27:01 +02:00 committed by GitHub
parent 53e4085ddc
commit 1f613a082a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -316,15 +316,12 @@ pub fn (mut ctx Context) not_found() Result {
// TODO - test // TODO - test
// Sets a cookie // Sets a cookie
pub fn (mut ctx Context) set_cookie(cookie http.Cookie) { pub fn (mut ctx Context) set_cookie(cookie http.Cookie) {
mut cookie_data := []string{} cookie_raw := cookie.str()
mut secure := if cookie.secure { 'Secure;' } else { '' } if cookie_raw == '' {
secure += if cookie.http_only { ' HttpOnly' } else { ' ' } eprintln('error setting cookie: name of cookie is invalid')
cookie_data << secure return
if cookie.expires.unix > 0 {
cookie_data << 'expires=${cookie.expires.utc_string()}'
} }
data := cookie_data.join(' ') ctx.add_header('Set-Cookie', cookie_raw)
ctx.add_header('Set-Cookie', '${cookie.name}=${cookie.value}; ${data}')
} }
// Sets the response content type // Sets the response content type
@ -333,27 +330,20 @@ pub fn (mut ctx Context) set_content_type(typ string) {
} }
// TODO - test // 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) { 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 // Gets a cookie by a key
pub fn (ctx &Context) get_cookie(key string) !string { // TODO refactor pub fn (ctx &Context) get_cookie(key string) !string {
mut cookie_header := ctx.get_header('cookie') if value := ctx.req.cookies[key] {
if cookie_header == '' { return value
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()
} }
return error('Cookie not found') return error('Cookie not found')
} }