From b698fc6b8809cc018f14c2255d674b0c51ce2e9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauri=20V=C3=B5sandi?= Date: Thu, 8 Jul 2021 13:48:58 +0300 Subject: [PATCH] Handle missing/empty `shortener.url` --- main.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index 62fda77..7cf7c9a 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/client_golang/prometheus/promhttp" "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/x/mongo/driver/connstring" @@ -17,13 +18,12 @@ import ( "time" ) -type shortenerAttrType struct { - Slug string - URL string -} - type inventoryItemType struct { - Shortener shortenerAttrType + ID primitive.ObjectID `bson:"_id" json:"_id,omitempty"` + Shortener struct { + Slug string `bson:"slug" json:"slug"` + URL string `bson:"url" json:"url"` + } `bson:"shortener" json:"shortener"` } var reValid = regexp.MustCompile("^[a-zA-Z0-9]{4,6}$") @@ -58,6 +58,9 @@ func wrapper(coll *mongo.Collection) func(w http.ResponseWriter, r *http.Request counterFound.Inc() var u = doc.Shortener.URL + if u == "" { + u = strings.Replace(redirectFound, "%s", doc.ID.Hex(), 1) + } http.Redirect(w, r, u, 302) log.Printf("Redirecting %s to %s\n", slug, doc.Shortener.URL) }