Sfoglia il codice sorgente

refactor getpid out of add

raylu 14 anni fa
parent
commit
c96ff0fd7d
1 ha cambiato i file con 31 aggiunte e 26 eliminazioni
  1. 31 26
      main.go

+ 31 - 26
main.go

@@ -22,6 +22,33 @@ var templates map[string]*template.Template
 const debug = true
 var db *mysql.Client
 
+// given an id ('abcd1234'), return the pid (1)
+func getpid(id string) int {
+	query, err := db.Prepare("SELECT `pid` FROM `playlist` WHERE `id` = ?;")
+	if err != nil {
+		return -1
+	}
+	err = query.BindParams(id)
+	if err != nil {
+		return -1
+	}
+	err = query.Execute()
+	if err != nil {
+		return -1
+	}
+	var pid int
+	query.BindResult(&pid)
+	_, err = query.Fetch()
+	if err != nil {
+		return -1
+	}
+	err = query.FreeResult()
+	if err != nil {
+		return -1
+	}
+	return pid
+}
+
 func home(w http.ResponseWriter, r *http.Request) {
 	fmt.Fprintf(w, "path is %s", r.URL.Path[1:])
 }
@@ -89,32 +116,10 @@ func playlist(w http.ResponseWriter, r *http.Request) {
 }
 
 func add(w http.ResponseWriter, r *http.Request) {
-	query, err := db.Prepare("SELECT `pid` FROM `playlist` WHERE `id` = ?;")
-	if err != nil {
-		http.Error(w, err.String(), http.StatusInternalServerError)
-		return
-	}
 	q := r.URL.Query()
-	err = query.BindParams(q.Get("pid"))
-	if err != nil {
-		http.Error(w, err.String(), http.StatusInternalServerError)
-		return
-	}
-	err = query.Execute()
-	if err != nil {
-		http.Error(w, err.String(), http.StatusInternalServerError)
-		return
-	}
-	var pid int
-	query.BindResult(&pid)
-	_, err = query.Fetch()
-	if err != nil {
-		http.Error(w, err.String(), http.StatusInternalServerError)
-		return
-	}
-	err = query.FreeResult()
-	if err != nil {
-		http.Error(w, err.String(), http.StatusInternalServerError)
+	pid := getpid(q.Get("pid"))
+	if pid == -1 {
+		http.Error(w, "invalid pid", http.StatusInternalServerError)
 		return
 	}
 
@@ -123,7 +128,7 @@ func add(w http.ResponseWriter, r *http.Request) {
 			db.Escape(q.Get("yid")),
 			db.Escape(q.Get("title")),
 			db.Escape(q.Get("user")))
-	err = db.Query(sql)
+	err := db.Query(sql)
 	if err != nil {
 		http.Error(w, err.String(), http.StatusInternalServerError)
 		return