From 82dd04f8aa7fba4d59de6e2d04853bbb8d7d87b6 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Sun, 14 Jul 2024 22:41:14 +0800 Subject: [PATCH] :sparkles: Forwarding requests --- pkg/hyper/conn.go | 6 +++++- pkg/internal/server/api/directory.go | 27 +++++++++++++++++++++++++++ pkg/internal/server/api/index.go | 2 ++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/pkg/hyper/conn.go b/pkg/hyper/conn.go index 88cfaf0..6ec14fd 100644 --- a/pkg/hyper/conn.go +++ b/pkg/hyper/conn.go @@ -53,9 +53,13 @@ func (v *HyperConn) KeepRegisterService() error { time.Sleep(5 * time.Second) client := health.NewHealthClient(v.dealerConn) if _, err := client.Check(context.Background(), &health.HealthCheckRequest{}); err != nil { - return v.KeepRegisterService() + if v.KeepRegisterService() == nil { + break + } } } + + return nil } func (v *HyperConn) GetServiceGrpcConn(t string) (*grpc.ClientConn, error) { diff --git a/pkg/internal/server/api/directory.go b/pkg/internal/server/api/directory.go index 4286801..7435327 100644 --- a/pkg/internal/server/api/directory.go +++ b/pkg/internal/server/api/directory.go @@ -3,7 +3,10 @@ package api import ( "git.solsynth.dev/hydrogen/dealer/pkg/internal/directory" "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/proxy" + "github.com/rs/zerolog/log" "github.com/samber/lo" + "strings" ) func listExistsService(c *fiber.Ctx) error { @@ -17,3 +20,27 @@ func listExistsService(c *fiber.Ctx) error { } })) } + +func forwardServiceRequest(c *fiber.Ctx) error { + serviceType := c.Params("service") + + service := directory.GetServiceInstanceByType(serviceType) + + if service == nil || service.HttpAddr == nil { + return fiber.NewError(fiber.StatusNotFound, "service not found") + } + + ogUrl := c.Request().URI().String() + url := c.OriginalURL() + url = strings.Replace(url, "/srv/"+serviceType, "", 1) + url = "http://" + *service.HttpAddr + url + + log.Debug(). + Str("from", ogUrl). + Str("to", url). + Str("service", serviceType). + Str("id", service.ID). + Msg("Forwarding request for service...") + + return proxy.Do(c, url) +} diff --git a/pkg/internal/server/api/index.go b/pkg/internal/server/api/index.go index c722d76..f939e47 100644 --- a/pkg/internal/server/api/index.go +++ b/pkg/internal/server/api/index.go @@ -12,6 +12,8 @@ func MapAPIs(app *fiber.App) { wellKnown.Get("/directory/services", listExistsService) } + app.All("/srv/:service/*", forwardServiceRequest) + api := app.Group("/api").Name("API") { api.Use(func(c *fiber.Ctx) error {