• 运行多个服务

    运行多个服务

    请参阅 issues 并尝试以下示例:

    1. package main
    2. import (
    3. "log"
    4. "net/http"
    5. "time"
    6. "github.com/gin-gonic/gin"
    7. "golang.org/x/sync/errgroup"
    8. )
    9. var (
    10. g errgroup.Group
    11. )
    12. func router01() http.Handler {
    13. e := gin.New()
    14. e.Use(gin.Recovery())
    15. e.GET("/", func(c *gin.Context) {
    16. c.JSON(
    17. http.StatusOK,
    18. gin.H{
    19. "code": http.StatusOK,
    20. "error": "Welcome server 01",
    21. },
    22. )
    23. })
    24. return e
    25. }
    26. func router02() http.Handler {
    27. e := gin.New()
    28. e.Use(gin.Recovery())
    29. e.GET("/", func(c *gin.Context) {
    30. c.JSON(
    31. http.StatusOK,
    32. gin.H{
    33. "code": http.StatusOK,
    34. "error": "Welcome server 02",
    35. },
    36. )
    37. })
    38. return e
    39. }
    40. func main() {
    41. server01 := &http.Server{
    42. Addr: ":8080",
    43. Handler: router01(),
    44. ReadTimeout: 5 * time.Second,
    45. WriteTimeout: 10 * time.Second,
    46. }
    47. server02 := &http.Server{
    48. Addr: ":8081",
    49. Handler: router02(),
    50. ReadTimeout: 5 * time.Second,
    51. WriteTimeout: 10 * time.Second,
    52. }
    53. g.Go(func() error {
    54. return server01.ListenAndServe()
    55. })
    56. g.Go(func() error {
    57. return server02.ListenAndServe()
    58. })
    59. if err := g.Wait(); err != nil {
    60. log.Fatal(err)
    61. }
    62. }