Browse Source

обработка score перенесена в gamePost

toomanysugar 3 years ago
parent
commit
3c2e37fa8b
2 changed files with 18 additions and 7 deletions
  1. 16 5
      cmd/web/handlers.go
  2. 2 2
      ui/templates/index.html

+ 16 - 5
cmd/web/handlers.go

@@ -4,6 +4,7 @@ import (
 	//"html/template"
 	"net/http"
 	"fmt"
+	"strconv"
 )
 
 func indexHandler(w http.ResponseWriter, r *http.Request) {
@@ -72,7 +73,8 @@ func logInPostHandler(w http.ResponseWriter, r *http.Request) {
 	r.ParseForm()
 	username := r.PostForm.Get("username")
 	password := r.PostForm.Get("password")
-
+	fmt.Printf("Post from website! r.PostFrom = %v\n", r.PostForm)
+	
 	if (dBConnector.LogIn(username, password)){
 
 		session, _ := sessionsStore.Get(r, "session")
@@ -80,7 +82,6 @@ func logInPostHandler(w http.ResponseWriter, r *http.Request) {
 		session.Values["password"] = password
 
 		session.Save(r,w)
-		fmt.Printf("%s\n%s\n",username,password)
 		http.Redirect(w, r, "/", http.StatusFound)
 	} else {
 		data := struct {
@@ -96,6 +97,7 @@ func logInPostHandler(w http.ResponseWriter, r *http.Request) {
 		logInTemplate.Execute(w, data)
 		//w.Write([]byte("Login error"))
 	}
+	
 }
 
 func logOutGetHandler(w http.ResponseWriter, r *http.Request) {
@@ -168,7 +170,16 @@ func gamePostHandler(w http.ResponseWriter, r *http.Request){ //TODO запис
 		return
 	}
 	fmt.Printf("Post from website! r.PostFrom = %v\n", r.PostForm)
-	score := r.FormValue("score")
-	fmt.Fprintf(w,"score = %s\n", score)
-	fmt.Printf("score = %s\n", score)
+	score_str := r.FormValue("score")
+	fmt.Fprintf(w,"score = %s\n", score_str)
+	fmt.Printf("score = %s\n", score_str)
+	score_int, err := strconv.Atoi(score_str)
+    if err != nil {
+        // handle error
+        fmt.Println(err)
+        logger.Printf("Error extracting score from '%s'",score_str)
+        //os.Exit(2)
+    } else {
+    	dBConnector.SubmitScore(score_int)
+    }
 }

+ 2 - 2
ui/templates/index.html

@@ -8,9 +8,9 @@
 		function post()
 		{
 		  var xhr = new XMLHttpRequest();// Создаём объект xhr
-		  xhr.open("POST", "/" , true);// Открываем асинхронное соединение
+		  xhr.open("POST", "/game/" , true);// Открываем асинхронное соединение
 		  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");// Отправляем кодировку
-		  var data = 'score=500';
+		  var data = 'score=' + Math.floor(Math.random()*1000);
 		  xhr.send(data); // Отправляем POST-запрос
 		  xhr.onreadystatechange = function() // Ждём ответа от сервера
 		  {