| 1 | import time |
| 2 | import 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 | |
| 16 | pub struct Context { |
| 17 | veb.Context |
| 18 | } |
| 19 | |
| 20 | pub 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] |
| 28 | pub fn (app &App) time() veb.Result { |
| 29 | return ctx.json({ |
| 30 | 'time': time.now().format_ss_milli() |
| 31 | }) |
| 32 | } |
| 33 | |
| 34 | fn main() { |
| 35 | println(" |
| 36 | To test if CORS works, copy this JS snippet, then go to for example https://stackoverflow.com/ , |
| 37 | press F12, then paste the snippet in the opened JS console. You should see the veb server's time: |
| 38 | var xhr = new XMLHttpRequest(); |
| 39 | xhr.onload = function(data) { |
| 40 | console.log('xhr loaded'); |
| 41 | console.log(xhr.response); |
| 42 | }; |
| 43 | xhr.open('POST', 'http://localhost:45678/time'); |
| 44 | xhr.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 | |