github.com/ergo-services/ergo@v1.999.224/tests/web_test.go (about) 1 package tests 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "net/http" 7 "testing" 8 9 "github.com/ergo-services/ergo" 10 "github.com/ergo-services/ergo/etf" 11 "github.com/ergo-services/ergo/gen" 12 "github.com/ergo-services/ergo/node" 13 ) 14 15 var ( 16 testWebString = "hello world" 17 ) 18 19 type testWebHandler struct { 20 gen.WebHandler 21 } 22 23 func (r *testWebHandler) HandleRequest(process *gen.WebHandlerProcess, request gen.WebMessageRequest) gen.WebHandlerStatus { 24 request.Response.Write([]byte(testWebString)) 25 return gen.WebHandlerStatusDone 26 } 27 28 type testWebServer struct { 29 gen.Web 30 } 31 32 func (w *testWebServer) InitWeb(process *gen.WebProcess, args ...etf.Term) (gen.WebOptions, error) { 33 var options gen.WebOptions 34 35 mux := http.NewServeMux() 36 webHandler := process.StartWebHandler(&testWebHandler{}, gen.WebHandlerOptions{}) 37 mux.Handle("/", webHandler) 38 options.Handler = mux 39 40 return options, nil 41 } 42 43 func TestWeb(t *testing.T) { 44 fmt.Printf("\n=== Test Web Server\n") 45 fmt.Printf("Starting nodes: nodeWeb1@localhost: ") 46 node1, err := ergo.StartNode("nodeWeb1@localhost", "cookies", node.Options{}) 47 defer node1.Stop() 48 if err != nil { 49 t.Fatal("can't start node", err) 50 } else { 51 fmt.Println("OK") 52 } 53 54 fmt.Printf("...starting process (gen.Web): ") 55 _, err = node1.Spawn("web", gen.ProcessOptions{}, &testWebServer{}) 56 if err != nil { 57 t.Fatal(err) 58 } 59 fmt.Println("OK") 60 61 fmt.Printf("...making simple GET request: ") 62 res, err := http.Get("http://localhost:8080") 63 if err != nil { 64 t.Fatal(err) 65 } 66 out, err := ioutil.ReadAll(res.Body) 67 if err != nil { 68 t.Fatal(err) 69 } 70 if string(out) != testWebString { 71 t.Fatal("mismatch result") 72 } 73 fmt.Println("OK") 74 }