本文主要是介绍gin框架33--运行多个服务,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
gin框架33--运行多个服务
- 介绍
- 案例
- 说明
介绍
本文介绍如何在gin框架中 运行多个服务, 每个服务对应不同的端口。
案例
源码:
package mainimport ("log""net/http""time""github.com/gin-gonic/gin""golang.org/x/sync/errgroup"
)var (g errgroup.Group
)func router01() http.Handler {e := gin.New()e.Use(gin.Recovery())e.GET("/", func(c *gin.Context) {c.JSON(http.StatusOK,gin.H{"code": http.StatusOK,"msg": "Welcome server 01",},)})return e
}func router02() http.Handler {e := gin.New()e.Use(gin.Recovery())e.GET("/", func(c *gin.Context) {c.JSON(http.StatusOK,gin.H{"code": http.StatusOK,"msg": "Welcome server 02",},)})return e
}func main() {server01 := &http.Server{Addr: ":8080",Handler: router01(),ReadTimeout: 5 * time.Second,WriteTimeout: 10 * time.Second,}server02 := &http.Server{Addr: ":8081",Handler: router02(),ReadTimeout: 5 * time.Second,WriteTimeout: 10 * time.Second,}g.Go(func() error {return server01.ListenAndServe()})g.Go(func() error {return server02.ListenAndServe()})if err := g.Wait(); err != nil {log.Fatal(err)}
}
测试:
http://127.0.0.1:8080/
{"code": 200,"msg": "Welcome server 01"
}http://127.0.0.1:8081/
{"code": 200,"msg": "Welcome server 02"
}
说明
gin官方文档 运行多个服务
这篇关于gin框架33--运行多个服务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!