Skip to content

Commit

Permalink
feat: some error handling for missing object
Browse files Browse the repository at this point in the history
  • Loading branch information
Firgrep committed May 23, 2024
1 parent 7bcb69d commit eda8c59
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 14 deletions.
4 changes: 3 additions & 1 deletion cspell.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
"version": "0.2",
"ignorePaths": [],
"ignorePaths": [
"**.go"
],
"dictionaryDefinitions": [],
"dictionaries": [],
"words": [
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ require (
github.com/google/uuid v1.6.0 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
github.com/googleapis/gax-go/v2 v2.12.4 // indirect
github.com/joho/godotenv v1.5.1 // indirect
go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfF
github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0=
github.com/googleapis/gax-go/v2 v2.12.4 h1:9gWcmF85Wvq4ryPFvGFaOgPIs1AQX0d0bcbGw4Z96qg=
github.com/googleapis/gax-go/v2 v2.12.4/go.mod h1:KYEYLorsnIGDi/rPC8b5TdlB9kbKoFubselGIoBMCwI=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
Expand Down
60 changes: 47 additions & 13 deletions main.go → server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,19 @@ import (
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"time"

"cloud.google.com/go/storage"
"github.com/joho/godotenv"
)

// bucket := "symposia-dev-bucket"
//
// object := "cluvqhyly0007uwfdmg2hn33a/VID_20200103_135115.mp4"
//
// generateV4GetObjectSignedURL generates object signed URL with GET method.
func generateV4GetObjectSignedURL(w io.Writer, bucket, object string) (string, error) {
// bucket := "bucket-name"
// object := "object-name"
var REQUIRED_VARS = []string{"PORT", "GCP_PRIMARY_BUCKET_NAME", "GCP_SECONDARY_BUCKET_NAME"}

func generateV4GetObjectSignedURL(w io.Writer, bucket, object string) (string, error) {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
Expand All @@ -41,9 +39,19 @@ func generateV4GetObjectSignedURL(w io.Writer, bucket, object string) (string, e
Expires: time.Now().Add(15 * time.Minute),
}

blob := client.Bucket(bucket).Object(object)

// Check if the object exists
_, err = blob.Attrs(ctx)

if err != nil {
fmt.Fprintf(w, "No object found: %s", http.StatusText(http.StatusNotFound))
return "", nil
}

u, err := client.Bucket(bucket).SignedURL(object, opts)
if err != nil {
return "", fmt.Errorf("Bucket(%q).SignedURL: %w", bucket, err)
return "Error creating signed URL", fmt.Errorf("Bucket(%q).SignedURL: %w", bucket, err)
}

fmt.Fprintln(w, "Generated GET signed URL:")
Expand All @@ -53,11 +61,37 @@ func generateV4GetObjectSignedURL(w io.Writer, bucket, object string) (string, e
return u, nil
}
func main() {
/*
Validate and load environment variables
*/
err := godotenv.Load()
if err != nil {
log.Printf("[Server] No env file found, attempting to use system environment variables.")
}
var missingVars []string
for _, varName := range REQUIRED_VARS {
value := os.Getenv(varName)
if value == "" {
missingVars = append(missingVars, varName)
}
}
if len(missingVars) > 0 {
errorMessage := fmt.Sprintf("[Server] [ERROR] Missing required environment variables: %s\nPlease set these variables in your .env file or system environment.", strings.Join(missingVars, ", "))
log.Fatal(errorMessage)
}
port := os.Getenv("PORT")
bucket := os.Getenv("GCP_PRIMARY_BUCKET_NAME")
/*
Start server
*/
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
bucket := "symposia-dev-bucket"
object := "video/cluvqhyly0007uwfdmg2hn33a/VID_20200103_135115.mp4"
object := r.URL.Path[1:] // Get the object from the request URL path
if object == "" {
http.Error(w, "Object not found.", http.StatusNotFound)
return
}
generateV4GetObjectSignedURL(w, bucket, object)
})
fmt.Println("Server listening on port 8080")
http.ListenAndServe(":8080", nil)
fmt.Println("[Server] Listening on port 8080")
http.ListenAndServe(":"+port, nil)
}

0 comments on commit eda8c59

Please sign in to comment.