github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/internal/test/server/http_server_test.go (about) 1 package server 2 3 import ( 4 "sync" 5 "testing" 6 "time" 7 8 "github.com/volts-dev/volts" 9 "github.com/volts-dev/volts/client" 10 "github.com/volts-dev/volts/internal/test" 11 "github.com/volts-dev/volts/router" 12 "github.com/volts-dev/volts/router/middleware/event" 13 "github.com/volts-dev/volts/server" 14 ) 15 16 func TestBase(t *testing.T) { 17 r := router.New() 18 r.Url("GET", "/", func(ctx *router.THttpContext) { 19 ctx.Write([]byte("Hello World!")) 20 }) 21 r.Url("GET", "/1", test.CtrlWithMiddleware.HelloWorld) 22 r.Url("GET", "/WithoutMiddlware", test.CtrlWithMiddleware.WithoutMiddlware) 23 24 r.RegisterMiddleware(event.NewEvent) 25 r.RegisterMiddleware(test.NewTestSession) 26 27 srv := server.New( 28 server.WithRouter(r), 29 server.Debug(), 30 ) 31 32 var g sync.WaitGroup 33 g.Add(1) 34 go func() { 35 if err := srv.Start(); err != nil { 36 srv.Stop() 37 g.Done() 38 } 39 }() 40 41 go func() { 42 // 等待就绪 43 for { 44 if srv.Started() { 45 g.Done() 46 break 47 } 48 49 time.Sleep(500) 50 } 51 }() 52 g.Wait() 53 54 cli, err := client.NewHttpClient( 55 client.WithHost(srv.Config().Address), 56 ) 57 if err != nil { 58 t.Fatal(err) 59 } 60 req, err := cli.NewRequest("GET", "http://localhost:35999/WithoutMiddlware", nil) 61 if err != nil { 62 t.Fatal(err) 63 } 64 resp, err := cli.Call(req) 65 if err != nil { 66 t.Fatal(err) 67 } 68 result := resp.Body().Data.String() 69 if result != "Hello World!" { 70 t.Log(result) 71 } 72 } 73 74 func TestProxy(t *testing.T) { 75 r := router.New() 76 r.Url("GET", "/", router.HttpReverseProxy) 77 78 srv := server.New( 79 server.WithRouter(r), 80 ) 81 82 app := volts.New( 83 volts.Server(srv), 84 //volts.Transport(transport.NewTCPTransport()), 85 volts.Debug(), 86 ) 87 88 app.Run() 89 90 } 91 func TestRecover(t *testing.T) { 92 r := router.New() 93 r.Url("GET", "/", func(ctx *router.THttpContext) { 94 p := ctx.PathParams() 95 p.FieldByName("query").AsString() 96 }) 97 98 srv := server.New( 99 server.WithRouter(r), 100 ) 101 102 app := volts.New( 103 volts.Server(srv), 104 //volts.Transport(transport.NewTCPTransport()), 105 volts.Debug(), 106 ) 107 108 app.Run() 109 110 }