From 13a93e0a9c7bc715c310fe0b3f60e6440f81ac9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcus=20Ziad=C3=A9?= Date: Thu, 31 Aug 2023 22:09:30 +0300 Subject: [PATCH] Refactor code to handle case when API key is not provided --- Dockerfile | 33 ++++++++++++++------------------- config.go | 7 ++++++- main.go | 5 ++++- 3 files changed, 24 insertions(+), 21 deletions(-) diff --git a/Dockerfile b/Dockerfile index 99205da..01ad21e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,32 +1,27 @@ -# Use the official Go image -FROM golang:1.19 AS build +# Use the official Golang image to create a build artifact. +FROM golang:1.19 as builder # Set the working directory WORKDIR /app -# Copy go mod and sum files -COPY go.mod go.sum ./ +# Copy the Go Modules manifests +COPY go.mod go.mod +COPY go.sum go.sum # Download dependencies RUN go mod download -# Copy source code +# Copy the source code COPY . . -# Build the application -RUN go build -o main . +# Build +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o /app/main . -# Use a lightweight image for deployment -FROM alpine:latest AS runtime +# Use a minimal image for deployment +FROM alpine:latest -# Install necessary libraries -RUN apk --no-cache add ca-certificates +# Copy the binary +COPY --from=builder /app/main /app/main -# Copy binary -COPY --from=build /app/main /app/ - -# Set the working directory -WORKDIR /app - -# Run the application -CMD [". --download-only"] +# This is the entry point, specify your flags here +ENTRYPOINT [ "/app/main", "--download-only" ] diff --git a/config.go b/config.go index 8e6ee78..630a1cf 100644 --- a/config.go +++ b/config.go @@ -14,6 +14,11 @@ type Config struct { } func getOrCreateAPIKey() string { + apiKey := os.Getenv("NASA_API_KEY") + if apiKey != "" { + return apiKey + } + filePathName := "Keys.json" config, err := readConfig(filePathName) if err != nil { @@ -42,7 +47,7 @@ func getOrCreateAPIKey() string { log.Fatalf("Error reading Keys.json: %v", err) } - apiKey := config.APIKey + apiKey = config.APIKey return apiKey } diff --git a/main.go b/main.go index 90c0ff1..beeb4ed 100644 --- a/main.go +++ b/main.go @@ -22,7 +22,10 @@ type NasaAPOD struct { const apiURL = "https://api.nasa.gov/planetary/apod" func main() { - apiKey := getOrCreateAPIKey() + apiKey := os.Getenv("NASA_API_KEY") + if apiKey == "" { + apiKey = getOrCreateAPIKey() + } start, end, downloadOnly := parseArgumentsForDateRange()