v2 / examples / veb / cors / veb_cors_example.v
58 lines · 48 sloc · 1.69 KB · 26ab7d4fe109f6a4da68b2179f36bbc8d9b9e0bd
Raw
1import time
2import veb
3
4// See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
5// and https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests
6// > Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows
7// > a server to indicate any origins (domain, scheme, or port) other than its own from
8// > which a browser should permit loading resources...
9
10// Usage: do `./v run examples/xveb/cors/` to start the app,
11// then check the headers in another shell:
12//
13// 1) `curl -vvv -X OPTIONS http://localhost:45678/time`
14// 2) `curl -vvv -X POST http://localhost:45678/time`
15
16pub struct Context {
17 veb.Context
18}
19
20pub struct App {
21 veb.Middleware[Context]
22}
23
24// time is a simple POST request handler, that returns the current time. It should be available
25// to JS scripts, running on arbitrary other origins/domains.
26
27@[post]
28pub fn (app &App) time() veb.Result {
29 return ctx.json({
30 'time': time.now().format_ss_milli()
31 })
32}
33
34fn main() {
35 println("
36To test if CORS works, copy this JS snippet, then go to for example https://stackoverflow.com/ ,
37press F12, then paste the snippet in the opened JS console. You should see the veb server's time:
38var xhr = new XMLHttpRequest();
39xhr.onload = function(data) {
40 console.log('xhr loaded');
41 console.log(xhr.response);
42};
43xhr.open('POST', 'http://localhost:45678/time');
44xhr.send();
45 ")
46
47 mut app := &App{}
48
49 // use veb's cors middleware to handle CORS requests
50 app.use(veb.cors[Context](veb.CorsOptions{
51 // allow CORS requests from every domain
52 origins: ['*']
53 // allow CORS requests with the following request methods:
54 allowed_methods: [.get, .head, .patch, .put, .post, .delete]
55 }))
56
57 veb.run[App, Context](mut app, 45678)
58}
59