目录

COOKBOOK(手册) - 子域名

优质
小牛编辑
135浏览
2023-12-01

子域名

server.go

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/labstack/echo"
  5. "github.com/labstack/echo/middleware"
  6. )
  7. type (
  8. Host struct {
  9. Echo *echo.Echo
  10. }
  11. )
  12. func main() {
  13. // Hosts
  14. hosts := make(map[string]*Host)
  15. //-----
  16. // API
  17. //-----
  18. api := echo.New()
  19. api.Use(middleware.Logger())
  20. api.Use(middleware.Recover())
  21. hosts["api.localhost:1323"] = &Host{api}
  22. api.GET("/", func(c echo.Context) error {
  23. return c.String(http.StatusOK, "API")
  24. })
  25. //------
  26. // Blog
  27. //------
  28. blog := echo.New()
  29. blog.Use(middleware.Logger())
  30. blog.Use(middleware.Recover())
  31. hosts["blog.localhost:1323"] = &Host{blog}
  32. blog.GET("/", func(c echo.Context) error {
  33. return c.String(http.StatusOK, "Blog")
  34. })
  35. //---------
  36. // Website
  37. //---------
  38. site := echo.New()
  39. site.Use(middleware.Logger())
  40. site.Use(middleware.Recover())
  41. hosts["localhost:1323"] = &Host{site}
  42. site.GET("/", func(c echo.Context) error {
  43. return c.String(http.StatusOK, "Website")
  44. })
  45. // Server
  46. e := echo.New()
  47. e.Any("/*", func(c echo.Context) (err error) {
  48. req := c.Request()
  49. res := c.Response()
  50. host := hosts[req.Host]
  51. if host == nil {
  52. err = echo.ErrNotFound
  53. } else {
  54. host.Echo.ServeHTTP(res, req)
  55. }
  56. return
  57. })
  58. e.Logger.Fatal(e.Start(":1323"))
  59. }