Selaa lähdekoodia

Replace certain character in filename

litpooh 3 vuotta sitten
vanhempi
commit
f57f693947
2 muutettua tiedostoa jossa 11 lisäystä ja 12 poistoa
  1. 3 4
      files/index.html
  2. 8 8
      main.go

+ 3 - 4
files/index.html

@@ -2,15 +2,14 @@
 <html>
     <head>
         <title>Index</title>
+        <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
+        </script>
     </head>
     <body>
         <p>INDEX</p>
 
     <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");

+ 8 - 8
main.go

@@ -2,10 +2,11 @@ package main
 
 import (
 	"flag"
+	"io/ioutil"
 	"log"
 	"math/rand"
 	"net/http"
-	"os"
+	"strings"
 	"time"
 )
 
@@ -24,18 +25,17 @@ func createHandler(rw http.ResponseWriter, req *http.Request) {
 	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)
-		}
+		// Filename cannot contain ":", so we need to replace them with "."
+		timestampNew := strings.ReplaceAll(timestamp.String(), ":", ".")
+
+		randomBytes := []byte(RandomString(8))
 
-		_, err = file.Write([]byte(RandomString(8)))
+		err := ioutil.WriteFile(timestampNew, randomBytes, 0644)
 		if err != nil {
 			log.Fatal(err)
 		}
 
-		file.Close()
-		log.Printf("A log file with filename %s is created.\n", timestamp.String())
+		log.Printf("A log file with filename %s is created.\n", timestampNew)
 
 	} else {
 		http.Error(rw, "Method "+req.Method+" is not supported", http.StatusNotFound)