Skip to content

x.vweb: add cors middleware#20713

Merged
spytheman merged 4 commits intovlang:masterfrom
Casper64:xvweb_cors
Feb 4, 2024
Merged

x.vweb: add cors middleware#20713
spytheman merged 4 commits intovlang:masterfrom
Casper64:xvweb_cors

Conversation

@Casper64
Copy link
Copy Markdown
Contributor

@Casper64 Casper64 commented Feb 2, 2024

fix for #20708

This pr adds a middleware function in x.vweb to handle CORS requests.
It also includes a small test and a modified example of examples/vweb/cors

CORS request can be traced by adding -d vweb_trace_cors when you compile

Usage

You only need to add vweb.cors as middleware to your app and configure CORS

Example:

import x.vweb

pub struct Context {
	vweb.Context
}

pub struct App {
	vweb.Middleware[Context]
}
fn main() {
	mut app := &App{}
	// use the cors middleware
	app.use(vweb.cors[Context](vweb.CorsOptions{
		origin: '*'
		allowed_methods: [.get, .head, .put, .post, .patch, .delete]
	}))

	vweb.run[App, Context](mut app, 8080)
}

Comment thread examples/xvweb/cors/vweb_cors_example.v Outdated
@enghitalo
Copy link
Copy Markdown
Contributor

enghitalo commented Feb 2, 2024

How will multiple origin cors works?

@Casper64
Copy link
Copy Markdown
Contributor Author

Casper64 commented Feb 2, 2024

How will multiple origin cors works?

Good suggestion, I can make the origin into an array.

From the MDN docs:

Only a single origin can be specified. If the server supports clients from multiple origins, it must return the origin for the specific client making the request.

@xqliang
Copy link
Copy Markdown

xqliang commented Feb 3, 2024

Yes should allow a list of hosts, and return the requested origin(even when the allowed host is *).

@spytheman spytheman marked this pull request as draft February 3, 2024 11:16
@Casper64 Casper64 marked this pull request as ready for review February 4, 2024 13:00
Comment thread vlib/x/vweb/middleware.v Outdated
@spytheman
Copy link
Copy Markdown
Contributor

@Casper64 , please run git pull --rebase origin master .

Co-authored-by: JalonSolov <JalonSolov@gmail.com>
@spytheman
Copy link
Copy Markdown
Contributor

Sorry, it was easier for me to do it.

@spytheman spytheman merged commit 4b46461 into vlang:master Feb 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants