From 80576ffa14795fe3d0368b6274ef0eba21d1deaa Mon Sep 17 00:00:00 2001 From: Jeremy Lewi Date: Mon, 22 Apr 2024 11:04:55 -0700 Subject: [PATCH] Use environment variables properly. --- app/pkg/logsviewer/client.go | 30 ++++++++++++++++++++++++++++++ app/pkg/logsviewer/selector.go | 13 +------------ 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/app/pkg/logsviewer/client.go b/app/pkg/logsviewer/client.go index 665bff8d..32b0c48c 100644 --- a/app/pkg/logsviewer/client.go +++ b/app/pkg/logsviewer/client.go @@ -3,9 +3,18 @@ package logsviewer import ( "context" "encoding/json" + "github.com/go-logr/zapr" "github.com/jlewi/foyle/app/api" + "github.com/maxence-charriere/go-app/v9/pkg/app" + "github.com/pkg/errors" + "go.uber.org/zap" "io" "net/http" + "strings" +) + +var ( + defaultClient *LogsClient ) // LogsClient client for the logs service. @@ -31,3 +40,24 @@ func (c *LogsClient) GetBlockLog(ctx context.Context, blockID string) (*api.Bloc } return block, nil } + +func GetClient() *LogsClient { + if defaultClient == nil { + log := zapr.NewLogger(zap.L()) + // N.B. I think using EndpointEnvVar is better using Window().Location().Href because of how we would deal with + // Reverse proxies. If we're behind some sort of reverse proxy we'd probably want the server to set the + // appropriate baseURL + endpoint := app.Getenv(EndpointEnvVar) + if endpoint == "" { + log.Error(errors.New("EndpointEnvVar is not set"), "Failed to create logsclient") + } + if !strings.HasSuffix(endpoint, "/") { + endpoint = endpoint + "/" + } + log.Info("Creating logs client", "endpoint", endpoint) + defaultClient = &LogsClient{ + Endpoint: endpoint, + } + } + return defaultClient +} diff --git a/app/pkg/logsviewer/selector.go b/app/pkg/logsviewer/selector.go index c3c08e37..2c6b3add 100644 --- a/app/pkg/logsviewer/selector.go +++ b/app/pkg/logsviewer/selector.go @@ -1,9 +1,7 @@ package logsviewer import ( - "github.com/go-logr/zapr" "github.com/maxence-charriere/go-app/v9/pkg/app" - "go.uber.org/zap" "strings" ) @@ -30,14 +28,7 @@ func (h *blockSelector) Render() app.UI { app.Button(). Text("Display"). OnClick(func(ctx app.Context, e app.Event) { - // Handle button click event here - // TODO(jeremy): Using os.Getenv is not working as a way of passing values from the server to the - // client. - // endpoint := os.Getenv(EndpointEnvVar) - endpoint := "http://localhost:8080/" - client := LogsClient{ - Endpoint: endpoint, - } + client := GetClient() blockID := app.Window().GetElementByID(blockInputID).Get("value").String() blockID = strings.TrimSpace(blockID) if blockID == "" { @@ -45,8 +36,6 @@ func (h *blockSelector) Render() app.UI { h.Update() return } - log := zapr.NewLogger(zap.L()) - log.Info("Fetching block log", "blockID", blockID, "endpoint", endpoint) blockLog, err := client.GetBlockLog(ctx, blockID) if err != nil { ctx.SetState(getErrorState, err.Error())