Kaynağa Gözat

Second commit

litpooh 4 yıl önce
ebeveyn
işleme
4a293b0b1a
3 değiştirilmiş dosya ile 70 ekleme ve 32 silme
  1. 11 4
      files/index.html
  2. 0 28
      folder.go
  3. 59 0
      main.go

+ 11 - 4
files/index.html

@@ -1,12 +1,19 @@
 <!DOCTYPE html>
 <html>
     <head>
-        <title>Example</title>
+        <title>Index</title>
     </head>
     <body>
         <p>INDEX</p>
     </body>
-    <form action="./create.html" method="get">
-        <input type="submit" value="Create a file">
-    </form>
+    <button onclick="myFunction()">Create a file</button>
+
+    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
+    </script>
+
+    <script>
+    function myFunction() {
+        $.get("/createfunction");
+    }
+    </script>
 </html>

+ 0 - 28
folder.go

@@ -1,28 +0,0 @@
-package main
-
-import (
-	"fmt"
-	"net/http"
-)
-
-func createHandler(rw http.ResponseWriter, req *http.Request) {
-	if req.Method == "GET" {
-		fmt.Fprintf(rw, "You requested the create-file function.")
-
-	} else {
-		responseText := fmt.Sprintf("Method %s is not supported.", req.Method)
-		http.Error(rw, responseText, http.StatusNotFound)
-		return
-	}
-}
-
-func main() {
-	port := "8000"
-	httpFileServer := http.FileServer(http.Dir("./files"))
-	http.Handle("/", httpFileServer)
-
-	fmt.Printf("Listening http://localhost:%s\n", port)
-	if error := http.ListenAndServe(":"+port, nil); error != nil {
-		fmt.Printf("Error: %s\n", error)
-	}
-}

+ 59 - 0
main.go

@@ -0,0 +1,59 @@
+package main
+
+import (
+	"flag"
+	"log"
+	"math/rand"
+	"net/http"
+	"os"
+	"time"
+)
+
+func RandomString(n int) string {
+	var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
+
+	s := make([]rune, n)
+	for i := range s {
+		s[i] = letters[rand.Intn(len(letters))]
+	}
+	return string(s)
+}
+
+func createHandler(rw http.ResponseWriter, req *http.Request) {
+	log.Println("Clicked!")
+	if req.Method == "GET" {
+		log.Println("You requested the create-file function.")
+		timestamp := time.Now()
+		file, err := os.OpenFile(timestamp.String()+".log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+		if err != nil {
+			log.Fatal(err)
+		}
+
+		_, err = file.Write([]byte(RandomString(8)))
+		if err != nil {
+			log.Fatal(err)
+		}
+
+		file.Close()
+		log.Printf("A log file with filename %s is created.\n", timestamp.String())
+
+	} else {
+		http.Error(rw, "Method "+req.Method+" is not supported", http.StatusNotFound)
+		return
+	}
+}
+
+func main() {
+	portPointer := flag.String("port", "8000", "An integer")
+	flag.Parse()
+	log.Println("Port Number: " + *portPointer)
+	httpFileServer := http.FileServer(http.Dir("./files"))
+	http.Handle("/", httpFileServer)
+
+	http.HandleFunc("/createfunction", createHandler)
+
+	log.Printf("Listening http://localhost:%s\n", *portPointer)
+	if error := http.ListenAndServe(":"+*portPointer, nil); error != nil {
+		log.Printf("Error: %s\n", error)
+	}
+}