snippets

More or less useful code snippets
Log | Files | Refs

gimme.go (1722B)


      1 package main
      2 
      3 // gimme hosts a minimal page that lets you upload stuff from the web browser
      4 // directly to the host computer
      5 
      6 import (
      7 	"fmt"
      8 	"io"
      9 	"net/http"
     10 	"os"
     11 	"time"
     12 )
     13 
     14 var index []byte = []byte(`
     15 <!DOCTYPE html>
     16 <html lang="en">
     17 <head>
     18     <meta charset="UTF-8">
     19     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     20     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     21     <title>Del filer</title>
     22 </head>
     23 <body>
     24     <input id="image-file" type="file" />
     25     <button onclick="upload()">Last opp</button>
     26     <script type="text/javascript">
     27         function upload() {
     28             let photo = document.getElementById("image-file").files[0];
     29             let formData = new FormData();
     30             formData.append("file", photo);
     31             fetch('/upload', {method: "POST", body: formData});
     32         }
     33     </script>
     34 </body>
     35 </html>
     36 `)
     37 
     38 func handleSite(w http.ResponseWriter, r *http.Request) {
     39 	w.Write(index)
     40 }
     41 
     42 func handleUpload(w http.ResponseWriter, r *http.Request) {
     43 	file, header, err := r.FormFile("file")
     44 	if err != nil {
     45 		w.WriteHeader(http.StatusInternalServerError)
     46 		fmt.Println("Error:", err)
     47 		return
     48 	}
     49 	fmt.Println(header.Filename)
     50 	fileContents, err := io.ReadAll(file)
     51 	if err != nil {
     52 		w.WriteHeader(http.StatusInternalServerError)
     53 		fmt.Println("Error:", err)
     54 		return
     55 	}
     56 	fmt.Println(time.Now())
     57 	fmt.Println(len(fileContents))
     58 	os.WriteFile("/tmp/gimme/"+header.Filename, fileContents, 0644)
     59 	//body.
     60 	//	fmt.Println(len(body))
     61 }
     62 
     63 func main() {
     64 	http.HandleFunc("/", handleSite)
     65 	http.HandleFunc("/upload", handleUpload)
     66 	fmt.Println("Starting server at port 8888")
     67 	if err := http.ListenAndServe(":8888", nil); err != nil {
     68 		fmt.Println(err)
     69 		os.Exit(1)
     70 	}
     71 }