Golang中如何将HTTP端点迁移到不同端口
Golang中如何将HTTP端点迁移到不同端口 我有一个实验性的HTTP服务,它在一个端口上有两个端点("/" 和 “/heartbeat”),并且优雅关闭功能运行良好。但我不知道如何将“/heartbeat”端点移动到另一个端口。
package main
// example from
// https://github.com/gin-gonic/examples/blob/master/graceful-shutdown/graceful-shutdown/server.go
import (
"context"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/toorop/gin-logrus"
"net/http"
"os"
"os/signal"
"syscall"
"time"
gin "github.com/gin-gonic/gin"
)
func WaitResponse(w string) string {
此文件已被截断。显示原文
提前感谢任何建议!
更多关于Golang中如何将HTTP端点迁移到不同端口的实战教程也可以访问 https://www.itying.com/category-94-b0.html
谢谢!我现在就试试看:)
感谢您的帮助!我之前尝试过您的建议,但结果发现我还必须将新服务器放入另一个
go func ()
...
如果您好奇的话,链接现在包含了有效的更改。
好的,没问题。基本的解决方案保持不变,您需要启动第二个服务器来监听不同的端口。
以下是您使用 Gin 框架的代码中的相关行:
srv := &http.Server{
Addr: ":8080",
Handler: router,
}
如果您想在 8080 端口之外监听另一个端口,您需要创建第二个服务器。
关于如何实现这一点,请参阅 https://github.com/gin-gonic/gin#run-multiple-service-using-gin。
你的代码片段中未显示的关键行是这些:
m := http.NewServeMux()
srv := http.Server{Addr: ":8080", Handler: m}
m.HandleFunc("/", TestEndpoint)
你将 http.Server 绑定的端口设置为 8080。如果你想绑定到第二个端口,就必须启动第二个服务器。
请注意,m.HandleFunc("/", TestEndpoint) 会匹配所有未被其他路由匹配的 URL。如果你只想精确匹配 /,就必须进行相应的检查。具体实现方法可以参考 https://golang.org/pkg/net/http/#example_ServeMux_Handle。
要实现将 /heartbeat 端点迁移到不同端口,需要创建两个独立的 HTTP 服务器实例。以下是基于你现有代码的修改方案:
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
log "github.com/sirupsen/logrus"
"github.com/toorop/gin-logrus"
gin "github.com/gin-gonic/gin"
)
func main() {
// 创建主服务器(端口8080)
mainRouter := gin.New()
mainRouter.Use(ginlogrus.Logger(log.StandardLogger()), gin.Recovery())
mainRouter.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Main endpoint"})
})
mainServer := &http.Server{
Addr: ":8080",
Handler: mainRouter,
}
// 创建心跳服务器(端口8081)
heartbeatRouter := gin.New()
heartbeatRouter.Use(ginlogrus.Logger(log.StandardLogger()), gin.Recovery())
heartbeatRouter.GET("/heartbeat", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "healthy"})
})
heartbeatServer := &http.Server{
Addr: ":8081",
Handler: heartbeatRouter,
}
// 启动两个服务器
go func() {
log.Infof("Main server starting on port 8080")
if err := mainServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Main server failed: %v", err)
}
}()
go func() {
log.Infof("Heartbeat server starting on port 8081")
if err := heartbeatServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Heartbeat server failed: %v", err)
}
}()
// 优雅关闭处理
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Info("Shutting down servers...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 关闭心跳服务器
if err := heartbeatServer.Shutdown(ctx); err != nil {
log.Errorf("Heartbeat server forced shutdown: %v", err)
}
// 关闭主服务器
if err := mainServer.Shutdown(ctx); err != nil {
log.Errorf("Main server forced shutdown: %v", err)
}
log.Info("Servers exited properly")
}
如果你需要保持现有的 WaitResponse 函数,可以这样集成:
func WaitResponse(w string) string {
time.Sleep(2 * time.Second)
return fmt.Sprintf("Processed: %s", w)
}
func main() {
mainRouter := gin.New()
heartbeatRouter := gin.New()
// 主端点使用 WaitResponse
mainRouter.GET("/", func(c *gin.Context) {
result := WaitResponse("main request")
c.JSON(http.StatusOK, gin.H{"result": result})
})
// 心跳端点
heartbeatRouter.GET("/heartbeat", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "healthy", "timestamp": time.Now().Unix()})
})
// ... 其余服务器配置和优雅关闭代码保持不变
}
这种方案创建了两个独立的 Gin 路由器和 HTTP 服务器实例,每个监听不同的端口。优雅关闭功能会同时处理两个服务器的关闭流程,确保所有连接都能正确终止。


