From f76efa2af597c4ec544e851265f7181e589211f1 Mon Sep 17 00:00:00 2001 From: nick Date: Mon, 15 Jul 2024 18:01:50 +0900 Subject: [PATCH] feat: send host through c.Locals --- node/pkg/boot/boot.go | 18 ++++++++++++------ node/pkg/boot/peer/controller.go | 12 +++++++----- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/node/pkg/boot/boot.go b/node/pkg/boot/boot.go index 75f9581e6..d2469e5c9 100644 --- a/node/pkg/boot/boot.go +++ b/node/pkg/boot/boot.go @@ -22,12 +22,24 @@ const REFRESH_INTERVAL = 10 * time.Second func Run(ctx context.Context) error { log.Debug().Msg("Starting boot server") + + h, err := libp2pSetup.NewHost(ctx) + if err != nil { + log.Error().Err(err).Msg("Failed to make host") + return err + } + app, err := utils.Setup(ctx) if err != nil { log.Error().Err(err).Msg("Failed to setup boot server") return err } + app.Use(func(c *fiber.Ctx) error { + c.Locals("host", &h) + return c.Next() + }) + v1 := app.Group("/api/v1") v1.Get("/", func(c *fiber.Ctx) error { return c.SendString("Orakl Node Boot API") @@ -40,12 +52,6 @@ func Run(ctx context.Context) error { port = "8089" } - h, err := libp2pSetup.NewHost(ctx) - if err != nil { - log.Error().Err(err).Msg("Failed to make host") - return err - } - refreshTicker := time.NewTicker(REFRESH_INTERVAL) go func() { for { diff --git a/node/pkg/boot/peer/controller.go b/node/pkg/boot/peer/controller.go index eba05700c..6cc65735f 100644 --- a/node/pkg/boot/peer/controller.go +++ b/node/pkg/boot/peer/controller.go @@ -2,10 +2,10 @@ package peer import ( "bisonai.com/orakl/node/pkg/db" - libp2pSetup "bisonai.com/orakl/node/pkg/libp2p/setup" libp2pUtils "bisonai.com/orakl/node/pkg/libp2p/utils" "github.com/go-playground/validator" "github.com/gofiber/fiber/v2" + "github.com/libp2p/go-libp2p/core/host" "github.com/rs/zerolog/log" ) @@ -31,11 +31,13 @@ func sync(c *fiber.Ctx) error { return c.Status(fiber.StatusBadRequest).SendString("Failed to validate request") } - h, err := libp2pSetup.NewHost(c.Context(), libp2pSetup.WithHolePunch(), libp2pSetup.WithPort(0)) - if err != nil { - log.Error().Err(err).Msg("Failed to make host") - return c.Status(fiber.StatusInternalServerError).SendString("Failed to make host") + rawHost, ok := c.Locals("host").(*host.Host) + if !ok { + log.Error().Msg("Failed to get host") + return c.Status(fiber.StatusInternalServerError).SendString("Failed to get host") } + h := *rawHost + defer func() { closeErr := h.Close() if closeErr != nil {