diff --git a/vlib/vweb/tests/vweb_cookie_test.v b/vlib/vweb/tests/vweb_cookie_test.v new file mode 100644 index 0000000000..d48b9a592e --- /dev/null +++ b/vlib/vweb/tests/vweb_cookie_test.v @@ -0,0 +1,52 @@ +import vweb +import net.http + +const ( + port = 12380 +) + +struct App { + vweb.Context +} + +fn (mut app App) index() vweb.Result { + app.set_cookie(vweb.Cookie{ + name: 'darkmode' + value: '0' + path: '/' // <------ new + domain: '127.0.0.1' // <------ new + }) + + if cookie := app.get_cookie('darkmode') { + println(cookie) + } + + return app.html('

Hello world

') +} + +fn test_cookie() { + go vweb.run(&App{}, port) + resp := http.get('http://127.0.0.1:$port/') or { panic(err) } + darkmode := resp.cookies['darkmode'] or { panic('cookie not set') } + value := darkmode[0].ascii_str().int() + mut path := '' + mut domain := '' + path_index := darkmode.index('path=') or { panic("path doesn't exist") } + 5 + domain_index := darkmode.index('domain=') or { panic("domain doesn't exist") } + 7 + for ch in darkmode[path_index..] { + if ch == `;` { + break + } + path += ch.ascii_str() + } + for ch in darkmode[domain_index..] { + if ch == `;` { + break + } + domain += ch.ascii_str() + } + assert value == 0 + assert path == '/' + assert domain == '127.0.0.1' + println(resp.cookies) +} diff --git a/vlib/vweb/vweb.v b/vlib/vweb/vweb.v index 8c131f6e81..8e414e7c27 100644 --- a/vlib/vweb/vweb.v +++ b/vlib/vweb/vweb.v @@ -197,6 +197,8 @@ pub struct Cookie { name string value string expires time.Time + path string + domain string secure bool http_only bool } @@ -313,6 +315,8 @@ pub fn (mut ctx Context) not_found() Result { // Sets a cookie pub fn (mut ctx Context) set_cookie(cookie Cookie) { mut cookie_data := []string{} + cookie_data << 'path=$cookie.path;' + cookie_data << 'domain=$cookie.domain;' mut secure := if cookie.secure { 'Secure;' } else { '' } secure += if cookie.http_only { ' HttpOnly' } else { ' ' } cookie_data << secure