In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
这篇文章主要介绍"如何用GIN构建一个WEB服务",在日常操作中,相信很多人在如何用GIN构建一个WEB服务问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"如何用GIN构建一个WEB服务"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
快速启动一个 api
目录
├── api \\ 服务入口├── cmd \\ 服务启动入口├── config├── doc └── chaper1.md├── go.mod├── internal \\ 业务逻辑├── main.go├── pkg \\ 三方包初始化└── router \\ Api 路由
GIN && Cobra
一般 WEB 服务,都会包含多个模块: API 接口、定时任务、消费 MQ 常驻进程等等,在这种情况下,很显然直接使用 GIN 来启动就只能开启 API 模块,十分不便。
我们用 Cobra 来管理项目的启动,现在不用关心 Cobra 如何使用,现在要的是满足我们需求。
很多时候人会陷入到细节里,就无法宏观的把控全局设计。无论是做需求还是设计框架,都应该梳理整个流程,每个流程需要什么样的技术,而技术细节反而不是最需要关心的。互联网发展到今天,你遇到的问题一定有人遇到过要把关注点放到你的设计上。
初始化一个 rootCmd 来管理项目中所有的模块
// main.gofunc main() { cmd.Execute()}// cmd/root.govar rootCmd = &cobra.Command{ Use: "提供WebApi服务", Short: "webApi",}func init() { rootCmd.AddCommand(apiCmd)}func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println("[错误]启动失败:", err) }}// cmd/api.govar httpServer *http.Servervar apiCmd = &cobra.Command { Use: "api", Short: "apiCmd", Long: `apiCmd 提供api接口服务`, Run: func(cmd *cobra.Command, args []string) { address := fmt.Sprintf("%v:%v", "0.0.0.0", 8080) engine := gin.New() httpServer = &http.Server{ Addr: address, Handler: engine, IdleTimeout: time.Minute, } if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { fmt.Println("启动失败", err) }}, }}
这个时候启动一下, 可以看到需要传一个命令行参数:
➜ gin-web-layout git:(master) ✗ go run main.go webApiUsage: 提供WebApi服务 [command]Available Commands: api apiCmd completion Generate the autocompletion script for the specified shell help Help about any command
使用 go run main.go api 就可以启动服务了
➜ gin-web-layout git:(master) ✗ go run main.go api [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode)
首先开始接入路由, 所见即所得,能快速的看到自己写的成果
router/router.gofunc InitRouter(engine *gin.Engine) { engine.GET("/", func(c *gin.Context) { c.JSON(200, "ok") })}在 cmd/api.go 增加以下代码engine := gin.New()router.InitRouter(engine)
这样一个 hello world 就完成了,这个也是 gin 快速开始的内容。 启动后访问一下:
➜ gin-web-layout git:(master) ✗ curl http://0.0.0.0:8080 "ok"%
这个时候我们来完善一下启动模块的代码,加上平滑重启,设置 5 秒后退出
// cmd/api.go// 只展示核心代码,完整代码可以在 github 查看// 等待 5 秒 timeout = 5 *time.sencondfunc OnServiceStop(timeout time.Duration) { quit := make(chan os.Signal) signal.Notify(quit, signals.Get()...)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.