From 583d6abb8447e58a5d743853d803024106931821 Mon Sep 17 00:00:00 2001 From: Tom Andrade Date: Thu, 19 Sep 2019 12:43:05 +0200 Subject: [PATCH 1/5] minor logic refactor --- main.go | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/main.go b/main.go index 54e1933..6222b40 100644 --- a/main.go +++ b/main.go @@ -22,7 +22,7 @@ import ( "github.com/patrickmn/go-cache" ) -const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // Base strings for RandStringBytesMaskImprSrc +const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // Base strings for randStringBytesMaskImprSrc const ( letterIdxBits = 6 // 6 bits to represent a letter index letterIdxMask = 1<= 0; { From a7e7ac33eee247041391c5153f6498d31d594f1e Mon Sep 17 00:00:00 2001 From: Tom Andrade Date: Thu, 19 Sep 2019 12:48:25 +0200 Subject: [PATCH 2/5] Change html templating style --- main.go | 85 ++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 51 insertions(+), 34 deletions(-) diff --git a/main.go b/main.go index 6222b40..f78ea96 100644 --- a/main.go +++ b/main.go @@ -32,24 +32,38 @@ const appVersion = "1.0.1" var src = rand.NewSource(time.Now().UnixNano()) var pool = cache.New(240*time.Hour, 1*time.Hour) -var okTmpl = template.Must(template.ParseFiles("templates/ok.html")) -var indexTmpl = template.Must(template.ParseFiles("templates/index.html")) -var returnTmpl = template.Must(template.ParseFiles("templates/returnPage.html")) -var notFoundTmpl = template.Must(template.ParseFiles("templates/404.html")) -var badRequestTmpl = template.Must(template.ParseFiles("templates/400.html")) -var internalErrorTmpl = template.Must(template.ParseFiles("templates/500.html")) +var templates *template.Template +var allFiles []string + +func init() { + files, err := ioutil.ReadDir("templates") + if err != nil { + log.Fatalln(err) + } + for _, file := range files { + filename := file.Name() + if strings.HasSuffix(filename, ".html") { + allFiles = append(allFiles, "templates/"+filename) + } + } + templates, err = template.ParseFiles(allFiles...) + if err != nil { + log.Fatalln(err) + } +} func index(w http.ResponseWriter, r *http.Request) { - indexTmpl.Execute(w, indexTmpl) + t := templates.Lookup("index.html") + t.Execute(w, nil) } // get executes the GET command func get(key string) (string, bool) { value, status := pool.Get(key) - if status { - return value.(string), status + if !status { + return "", status } - return "", false + return value.(string), status } // set executes the redis SET command @@ -63,6 +77,7 @@ func set(key, suffix string) { func redirect(w http.ResponseWriter, r *http.Request, path string) { vals := mux.Vars(r) key := vals["key"] + t := templates.Lookup("404.html") if path != "" { key = strings.Replace(key, path, "", 1) } @@ -71,18 +86,14 @@ func redirect(w http.ResponseWriter, r *http.Request, path string) { key, status := get(key) if !status { w.WriteHeader(http.StatusNotFound) - notFoundTmpl.Execute(w, nil) + t.Execute(w, nil) return } - u, _ := url.Parse(key) - if u.Scheme == "" { - u.Scheme = "https" - } - http.Redirect(w, r, u.String(), http.StatusFound) - } else { - w.WriteHeader(http.StatusNotFound) - notFoundTmpl.Execute(w, notFoundTmpl) + u, _ := url.Parse(key) + if u.Scheme == "" { + u.Scheme = "https" } + http.Redirect(w, r, u.String(), http.StatusFound) } // shortner reads url from a POST request, validates the url, generate a @@ -91,24 +102,26 @@ func redirect(w http.ResponseWriter, r *http.Request, path string) { // then if writes the kv pair suffix, url to the database and return the // shortened url to the user func shortner(w http.ResponseWriter, r *http.Request, proto, domain, hostSuf, path string, urlSize int) { + ret := templates.Lookup("returnPage.html") + badR := templates.Lookup("400.html") if !govalidator.IsURL(r.FormValue("url")) { w.WriteHeader(http.StatusBadRequest) - badRequestTmpl.Execute(w, nil) + badR.Execute(w, nil) return } - u, _ := url.Parse(r.FormValue("url")) + u, _ := url.Parse(r.FormValue("url")) suffix := randStringBytesMaskImprSrc(urlSize) - for { - _, status := get(suffix) + for { + _, status := get(suffix) if !status { - break - } - suffix = randStringBytesMaskImprSrc(urlSize) + break } - set(u.String(), suffix) - shortend := proto + "://" + domain + hostSuf + path + suffix - returnTmpl.Execute(w, shortend) + suffix = randStringBytesMaskImprSrc(urlSize) + } + set(u.String(), suffix) + shortend := proto + "://" + domain + hostSuf + path + suffix + ret.Execute(w, shortend) } // randStringBytesMaskImprSrc Generate random string of n size @@ -132,9 +145,10 @@ func randStringBytesMaskImprSrc(n int) string { // internalError receives a http.ResponseWriter, msg and error and // return a internal error page with http code 500 to the user func internalError(w http.ResponseWriter, msg string, err error) { + t := templates.Lookup("500.html") log.Println(err) w.WriteHeader(http.StatusInternalServerError) - internalErrorTmpl.Execute(w, msg+err.Error()) + t.Execute(w, msg+err.Error()) } // itemsCount returns the number of kv pairs on the in meomry database @@ -163,6 +177,7 @@ func itemsDump(w http.ResponseWriter, r *http.Request) { // itemsFromFile loads kv pairs from the dumpFile json to the in memory database func itemsFromFile(w http.ResponseWriter, r *http.Request, dumpFile string) { + t := templates.Lookup("ok.html") jsonFile, err := ioutil.ReadFile(dumpFile) var dumpObj map[string]cache.Item json.Unmarshal([]byte(jsonFile), &dumpObj) @@ -170,12 +185,13 @@ func itemsFromFile(w http.ResponseWriter, r *http.Request, dumpFile string) { internalError(w, "Cannot open file "+dumpFile+": ", err) } else { pool = cache.NewFrom(240*time.Hour, 1*time.Hour, dumpObj) - okTmpl.Execute(w, "Imported "+strconv.Itoa(len(dumpObj))+" items to the DB") + t.Execute(w, "Imported "+strconv.Itoa(len(dumpObj))+" items to the DB") } } // itemsFromPost loads kv pairs from a json POST to the in memory database func itemsFromPost(w http.ResponseWriter, r *http.Request) { + t := templates.Lookup("ok.html") decoder := json.NewDecoder(r.Body) var dumpObj map[string]cache.Item err := decoder.Decode(&dumpObj) @@ -183,12 +199,13 @@ func itemsFromPost(w http.ResponseWriter, r *http.Request) { internalError(w, "Cannot parse JSON: ", err) } else { pool = cache.NewFrom(240*time.Hour, 1*time.Hour, dumpObj) - okTmpl.Execute(w, "Imported "+strconv.Itoa(len(dumpObj))+" items to the DB") + t.Execute(w, "Imported "+strconv.Itoa(len(dumpObj))+" items to the DB") } } // itemsDumpToFile dumps the kv pairs from the in memory database to the dumpFile func itemsDumpToFile(w http.ResponseWriter, r *http.Request, dumpFile string) { + t := templates.Lookup("ok.html") dumpObj, _ := json.Marshal( pool.Items(), ) @@ -196,7 +213,7 @@ func itemsDumpToFile(w http.ResponseWriter, r *http.Request, dumpFile string) { if err != nil { internalError(w, "Failed to open json file: ", err) } else { - okTmpl.Execute(w, "Dump writen to: "+dumpFile) + t.Execute(w, "Dump writen to: "+dumpFile) } } @@ -220,7 +237,7 @@ func main() { } if *port > 65535 || *port < 1 { - + log.Fatalln("Invalid port number") } if *path != "" && !strings.HasSuffix(*path, "/") { *path = *path + "/" From 42998fee7c32de12e7f0f728d90a87cf0bc083e8 Mon Sep 17 00:00:00 2001 From: Tom Andrade Date: Thu, 19 Sep 2019 12:49:27 +0200 Subject: [PATCH 3/5] update templates --- templates/400.html | 321 ++++---------------------------------- templates/404.html | 320 ++++--------------------------------- templates/500.html | 308 ++++-------------------------------- templates/footer.html | 5 + templates/header.html | 282 +++++++++++++++++++++++++++++++++ templates/index.html | 99 ++---------- templates/ok.html | 37 +---- templates/returnPage.html | 37 +---- templates/slimheader.html | 72 +++++++++ 9 files changed, 484 insertions(+), 997 deletions(-) create mode 100644 templates/footer.html create mode 100644 templates/header.html create mode 100644 templates/slimheader.html diff --git a/templates/400.html b/templates/400.html index 3837895..0184d44 100644 --- a/templates/400.html +++ b/templates/400.html @@ -1,293 +1,40 @@ - - Short: the simple url shortener - - - -
-
-

400

-

Bad Request

-
-
-
-
-
-
-
+ {{ template "header" }} + +
+
+

400

+

Bad Request

-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

Boo, looks like a ghost didn't like your request! +
+ But you can try again, type an URL below to shorten it

+
-
-
-
-

Boo, looks like a ghost didn't like your request! -
- But you can try again, type an URL below to shorten it

- -
- - \ No newline at end of file + {{ template "footer" }} + + \ No newline at end of file diff --git a/templates/404.html b/templates/404.html index a1b8efd..be7cd44 100644 --- a/templates/404.html +++ b/templates/404.html @@ -1,293 +1,41 @@ - - Short: the simple url shortener - - - -
-
-

404

-

page not found

-
-
-
-
-
-
-
+ +
+
+

404

+

page not found

-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

Boo, looks like a ghost stole this page! +
+ But you can type an URL below to shorten it

+
-
-
-
-

Boo, looks like a ghost stole this page! -
- But you can type an URL below to shorten it

- -
- - \ No newline at end of file + {{ template "footer" }} + + \ No newline at end of file diff --git a/templates/500.html b/templates/500.html index 615282d..df07b3a 100644 --- a/templates/500.html +++ b/templates/500.html @@ -1,287 +1,35 @@ - - Short: the simple url shortener - - - -
-
-

500

-

Internal server error

-
-
-
-
-
-
-
+ +
+
+

500

+

Internal server error

-
-
-

X

-

X

-
+
+
+
+
+
+
+
+
+

X

+

X

+
+
+
+
+
+
+

Boo, the ghost is broken :( +
+ His last words where: {{ . }}

-
-
-
-

Boo, the ghost is broken :( -
- His last words where: {{ . }}

-
- - \ No newline at end of file + {{ template "footer" }} + + \ No newline at end of file diff --git a/templates/footer.html b/templates/footer.html new file mode 100644 index 0000000..9e1b755 --- /dev/null +++ b/templates/footer.html @@ -0,0 +1,5 @@ +{{ define "footer" }} + +{{ end }} \ No newline at end of file diff --git a/templates/header.html b/templates/header.html new file mode 100644 index 0000000..6b2bb2a --- /dev/null +++ b/templates/header.html @@ -0,0 +1,282 @@ +{{ define "header" }} + + Short: the simple url shortener + + +{{ end }} diff --git a/templates/index.html b/templates/index.html index 866a0bb..b4e2f7b 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,87 +1,18 @@ - - Short: the simple url shortener - - - -
-

Welcome to Short, the simple URL shortener, -
- Type an URL below to shorten it

- -
- + {{ template "slimheader" }} + +
+

Welcome to Short, the simple URL shortener, +
+ Type an URL below to shorten it

+ +
+ {{ template "footer" }} + \ No newline at end of file diff --git a/templates/ok.html b/templates/ok.html index 15ba75b..ef328cc 100644 --- a/templates/ok.html +++ b/templates/ok.html @@ -1,33 +1,10 @@ - - Short: the simple url shortner - - - -
-

{{ . }}

-
- + {{ template "slimheader" }} + +
+

{{ . }}

+
+ {{ template "footer" }} + \ No newline at end of file diff --git a/templates/returnPage.html b/templates/returnPage.html index 748825a..f1bcfc0 100644 --- a/templates/returnPage.html +++ b/templates/returnPage.html @@ -1,33 +1,10 @@ - - Short: the simple url shortner - - - -
-

URL Shortened to {{ . }}

-
- + {{ template "slimheader" }} + +
+

URL Shortened to {{ . }}

+
+ {{ template "footer" }} + \ No newline at end of file diff --git a/templates/slimheader.html b/templates/slimheader.html new file mode 100644 index 0000000..21e877e --- /dev/null +++ b/templates/slimheader.html @@ -0,0 +1,72 @@ +{{ define "slimheader" }} + + Short: the simple url shortener + + +{{ end }} \ No newline at end of file From 10018b4d74d2b50e3c8b84878a2ca6284a76479d Mon Sep 17 00:00:00 2001 From: Tom Andrade Date: Thu, 19 Sep 2019 12:50:10 +0200 Subject: [PATCH 4/5] bump version to 1.1.0 --- main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.go b/main.go index f78ea96..98b310f 100644 --- a/main.go +++ b/main.go @@ -28,7 +28,7 @@ const ( letterIdxMask = 1< Date: Thu, 19 Sep 2019 12:57:28 +0200 Subject: [PATCH 5/5] bump golang build to 1.12.9 --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 4d55b14..623fc26 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.12.4 as builder +FROM golang:1.12.9 as builder ENV CGO_ENABLED=0