v4 / vlib / veb / tests / context_ip_test.v
52 lines · 43 sloc · 1.1 KB · 93c1fbf8255d1ca101c22a12d3381e93db72884c
Raw
1// vtest build: !windows // fasthttp.Server.run is not implemented on windows yet
2import net.http
3import time
4import veb
5
6const port = 13066
7const localserver = 'http://127.0.0.1:${port}'
8const exit_after = time.second * 10
9
10pub struct Context {
11 veb.Context
12}
13
14pub struct App {
15mut:
16 started chan bool
17}
18
19pub fn (mut app App) before_accept_loop() {
20 app.started <- true
21}
22
23pub fn (mut app App) index(mut ctx Context) veb.Result {
24 return ctx.text('ip=${ctx.ip()} conn_nil=${ctx.conn == unsafe { nil }}')
25}
26
27fn testsuite_begin() {
28 spawn fn () {
29 time.sleep(exit_after)
30 assert true == false, 'timeout reached!'
31 exit(1)
32 }()
33
34 mut app := &App{}
35 spawn veb.run_at[App, Context](mut app, port: port, timeout_in_seconds: 2, family: .ip)
36 _ := <-app.started
37}
38
39fn test_context_ip_uses_peer_ip_for_buffered_requests() {
40 res := http.get(localserver)!
41 assert res.body == 'ip=127.0.0.1 conn_nil=true'
42}
43
44fn test_context_ip_prefers_proxy_headers() {
45 res := http.fetch(
46 url: localserver
47 header: http.new_header_from_map({
48 .x_forwarded_for: '9.9.9.9, 8.8.8.8'
49 })
50 )!
51 assert res.body == 'ip=9.9.9.9 conn_nil=true'
52}
53