From 9065d990e5da4f28000e1223c93b93274a1bfed8 Mon Sep 17 00:00:00 2001 From: yusing Date: Mon, 30 Sep 2024 15:56:03 +0800 Subject: [PATCH] go-proxy ls-route now query api server first, then fallback to read from config file --- .github/workflows/docker-image.yml | 6 ------ Dockerfile | 4 ++-- cmd/main.go | 9 ++++++++- internal/api/v1/utils/localhost.go | 18 ++++++++++++++++++ 4 files changed, 28 insertions(+), 9 deletions(-) diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 8a875749..2aa8786e 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -124,9 +124,3 @@ jobs: - name: Inspect image run: | docker buildx imagetools inspect ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} - - - name: Tag as latest - if: startsWith(github.ref, 'refs/tags/') && !contains(github.ref_name, '-') - run: | - docker tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest - docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest diff --git a/Dockerfile b/Dockerfile index 6666618f..02e6eb6a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,11 +5,11 @@ RUN apk add --no-cache tzdata WORKDIR /src # Only copy go.mod and go.sum initially for better caching -COPY go.mod go.sum /src +COPY go.mod go.sum /src/ # Utilize build cache RUN --mount=type=cache,target="/go/pkg/mod" \ - go mod graph | awk '{if ($1 !~ "@") print $2}' | xargs go get + go mod download -x ENV GOCACHE=/root/.cache/go-build diff --git a/cmd/main.go b/cmd/main.go index 6149737d..f38a8c66 100755 --- a/cmd/main.go +++ b/cmd/main.go @@ -91,7 +91,14 @@ func main() { printJSON(cfg.Value()) return case common.CommandListRoutes: - printJSON(cfg.RoutesByAlias()) + routes, err := apiUtils.ListRoutes() + if err.HasError() { + log.Printf("failed to connect to api server: %s", err) + log.Printf("falling back to config file") + printJSON(cfg.RoutesByAlias()) + } else { + printJSON(routes) + } return case common.CommandDebugListEntries: printJSON(cfg.DumpEntries()) diff --git a/internal/api/v1/utils/localhost.go b/internal/api/v1/utils/localhost.go index 4c5dde1a..66e9070a 100644 --- a/internal/api/v1/utils/localhost.go +++ b/internal/api/v1/utils/localhost.go @@ -1,6 +1,7 @@ package utils import ( + "encoding/json" "fmt" "io" "net/http" @@ -29,3 +30,20 @@ func ReloadServer() E.NestedError { } return nil } + +func ListRoutes() (map[string]map[string]any, E.NestedError) { + resp, err := httpClient.Get(fmt.Sprintf("%s/v1/list/routes", common.APIHTTPURL)) + if err != nil { + return nil, E.From(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, E.Failure("list routes").Extraf("status code: %v", resp.StatusCode) + } + var routes map[string]map[string]any + err = json.NewDecoder(resp.Body).Decode(&routes) + if err != nil { + return nil, E.From(err) + } + return routes, nil +}