本文由golang教程栏目给大家介绍怎么用 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.go func main() { cmd.Execute()} // cmd/root.go var 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.go var httpServer *http.Server var 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 webApi Usage: 提供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.go func 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.sencond func OnServiceStop(timeout time.Duration) { quit := make(chan os.Signal) signal.Notify(quit, signals.Get()...) <-quit ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() err := httpServer.Shutdown(ctx) if err != nil { log.Fatalf("service stop error:%v", err) } log.Println("service is stopping") }
这样就支持了热启动,然后就编译启动,ctrl+c, 他为什么没阻塞 5 秒,直接就退出了?
因为 ctrl+c 的时候,会检查是否有待处理的请求,如没有就会直接退出。我们可以模拟一个耗时请求:
// router/router.go engine.GET("/", func(c *gin.Context) { time.Sleep(5 * time.Second) c.JSON(200, "ok") })
重新启动后,再次 ctrl+c 会发现 5 秒后项目才退出完成。
题外话,线上的服务是如何发布部署的?
一般线上服务都会用网关调度流量,当我们一个服务接受到 kill(重启脚本一般用 kill,杀掉 pid) 信号,就不再接受新请求。
这一点可以用我们刚配置的热重启验证一下,把 timeout 设置 10s, 伪造一个耗时 10s 的请求,启动后执行退出(用 ctrl+c 或者 kill, 本质都是发送一个信号), 然后再访问服务,
会得到
➜ gin-web-layout git:(master) ✗ curl http://0.0.0.0:8080 curl: (7) Failed to connect to 0.0.0.0 port 8080: Connection refused
网关和服务会有心跳监测,无法提供服务后,网关自动踢掉服务,不再发流量,待恢复后再重新发流量。但是实际部署部署是另有方案,因为心跳是有间隔的,这个间隔期间服务退出了,就会造成大量的 502
实际线上操作为,当一台服务要退出的时候,会先到网关摘流量,再执行平滑退出,启动新服务,到网关挂上流量。 网关一般用的是阿里的 slb,也有人用 kong,都是一样的套路。
The above is the detailed content of Teach you to build a WEB service using GIN. For more information, please follow other related articles on the PHP Chinese website!

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

ChooseGolangforhighperformanceandconcurrency,idealforbackendservicesandnetworkprogramming;selectPythonforrapiddevelopment,datascience,andmachinelearningduetoitsversatilityandextensivelibraries.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

In what aspects are Golang and Python easier to use and have a smoother learning curve? Golang is more suitable for high concurrency and high performance needs, and the learning curve is relatively gentle for developers with C language background. Python is more suitable for data science and rapid prototyping, and the learning curve is very smooth for beginners.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment