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. // 借助errgroup.Group或者自行开启两个goroutine分别启动两个服务
    54. g.Go(func() error {
    55. return server01.ListenAndServe()
    56. })
    57. g.Go(func() error {
    58. return server02.ListenAndServe()
    59. })
    60. if err := g.Wait(); err != nil {
    61. log.Fatal(err)
    62. }
    63. }