restful-multi-containers.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package main
  2. import (
  3. "github.com/emicklei/go-restful"
  4. "io"
  5. "log"
  6. "net/http"
  7. )
  8. // This example shows how to have a program with 2 WebServices containers
  9. // each having a http server listening on its own port.
  10. //
  11. // The first "hello" is added to the restful.DefaultContainer (and uses DefaultServeMux)
  12. // For the second "hello", a new container and ServeMux is created
  13. // and requires a new http.Server with the container being the Handler.
  14. // This first server is spawn in its own go-routine such that the program proceeds to create the second.
  15. //
  16. // GET http://localhost:8080/hello
  17. // GET http://localhost:8081/hello
  18. func main() {
  19. ws := new(restful.WebService)
  20. ws.Route(ws.GET("/hello").To(hello))
  21. restful.Add(ws)
  22. go func() {
  23. http.ListenAndServe(":8080", nil)
  24. }()
  25. container2 := restful.NewContainer()
  26. ws2 := new(restful.WebService)
  27. ws2.Route(ws2.GET("/hello").To(hello2))
  28. container2.Add(ws2)
  29. server := &http.Server{Addr: ":8081", Handler: container2}
  30. log.Fatal(server.ListenAndServe())
  31. }
  32. func hello(req *restful.Request, resp *restful.Response) {
  33. io.WriteString(resp, "default world")
  34. }
  35. func hello2(req *restful.Request, resp *restful.Response) {
  36. io.WriteString(resp, "second world")
  37. }