Quellcode durchsuchen

Don't crush on URL parsing

Piotr Czajkowski vor 1 Woche
Ursprung
Commit
3b595eaf1f
3 geänderte Dateien mit 47 neuen und 6 gelöschten Zeilen
  1. 27 0
      html/error.html
  2. 11 1
      server.go
  3. 9 5
      storage.go

+ 27 - 0
html/error.html

@@ -0,0 +1,27 @@
+<!doctype html>
+<html>
+	<head>
+		<meta charset="utf-8">
+		<script async src="https://cdn.ampproject.org/v0.js"></script>
+		<title>There was an error</title>
+		<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
+		<script type="application/ld+json">
+			{
+				"@context": "http://schema.org",
+				"@type": "NewsArticle",
+				"headline": "Open-source framework for publishing content",
+				"datePublished": "2015-10-07T12:02:41Z",
+				"image": [
+				"logo.jpg"
+				]
+			}
+		</script>
+		<link rel="stylesheet" href="https://newcss.net/lite.css">
+		<link rel="stylesheet" href="https://newcss.net/theme/night.css">
+
+	</head>
+	<body>
+		<p>{{.}}"</p>
+		<a href="/">Back to homepage.</a>
+	</body>
+</html>

+ 11 - 1
server.go

@@ -25,13 +25,23 @@ func init() {
 	toSave = make(chan string, 100)
 }
 
+func returnErorr(w http.ResponseWriter, err string) {
+	w.WriteHeader(http.StatusNotFound)
+	t := template.Must(template.ParseFiles("./html/error.html"))
+	t.Execute(w, err)
+}
+
 func shorten(w http.ResponseWriter, r *http.Request) {
 	link := r.URL.Query().Get("link")
 	if link == "" {
 		link = strings.TrimPrefix(r.URL.Path, shortenPath)
 	}
 
-	linkID := addLink(link, toSave)
+	addStatus, linkID := addLink(link, toSave)
+	if !addStatus {
+		returnErorr(w, linkID)
+		return
+	}
 
 	t := template.Must(template.ParseFiles("./html/result.html"))
 

+ 9 - 5
storage.go

@@ -50,10 +50,12 @@ func readLinks(path string) {
 
 }
 
-func addLink(link string, toSave chan<- string) string {
+func addLink(link string, toSave chan<- string) (bool, string) {
 	u, err := url.Parse(link)
 	if err != nil {
-		log.Printf("Error parsing link: %s", err)
+		m := fmt.Sprintf("Error parsing link: %s", err)
+		log.Println(m)
+		return false, m
 	}
 	link = u.String()
 
@@ -62,14 +64,16 @@ func addLink(link string, toSave chan<- string) string {
 	existingLink, loaded := links.LoadOrStore(linkID, link)
 	if loaded {
 		if existingLink != link {
-			log.Printf("Have collision:\n%s\n%s\n", link, existingLink)
+			m := "Can't add link."
+			log.Println(m)
+			return false, m
 		}
 
-		return linkID
+		return true, linkID
 	}
 
 	toSave <- fmt.Sprintf(format, linkID, link)
-	return linkID
+	return true, linkID
 }
 
 func getLink(linkID string) string {