11package cmd
22
33import (
4+ _ "embed"
45 "fmt"
56 "io"
6- "io/ioutil"
77 "net/http"
88 "os"
99 "path/filepath"
@@ -13,6 +13,9 @@ import (
1313 "github.com/spf13/cobra"
1414)
1515
16+ //go:embed static/upload.html
17+ var uploadHTML string
18+
1619var folder string
1720var filePath string
1821var port int
@@ -76,23 +79,7 @@ var startCmd = &cobra.Command{
7679}
7780
7881func uploadPage (w http.ResponseWriter , r * http.Request ) {
79- htmlContent := `<!DOCTYPE html>
80- <html lang="en">
81- <head>
82- <meta charset="UTF-8" />
83- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
84- <meta http-equiv="X-UA-Compatible" content="ie=edge" />
85- <title>Upload Files</title>
86- </head>
87- <body>
88- <form enctype="multipart/form-data" action="/api/upload" method="post">
89- <input type="file" multiple="multiple" name="files" />
90- <input type="submit" value="upload" />
91- </form>
92- </body>
93- </html>
94- `
95- w .Write ([]byte (htmlContent ))
82+ w .Write ([]byte (uploadHTML ))
9683}
9784
9885func uploadFile (w http.ResponseWriter , r * http.Request ) {
@@ -105,7 +92,7 @@ func uploadFile(w http.ResponseWriter, r *http.Request) {
10592 file , err := fh .Open ()
10693 if err != nil {
10794 fmt .Println (err )
108- w .WriteHeader (400 )
95+ w .WriteHeader (http . StatusBadRequest )
10996 w .Write ([]byte ("Error retrieving the file" ))
11097 return
11198 }
@@ -119,10 +106,10 @@ func uploadFile(w http.ResponseWriter, r *http.Request) {
119106 fmt .Printf ("MIME type: %+v\n " , fh .Header ["Content-Type" ])
120107
121108 // 3. write temporary file on our server
122- tempFile , err := ioutil . TempFile ("" , "http-upload-*" )
109+ tempFile , err := os . CreateTemp ("" , "http-upload-*" )
123110 if err != nil {
124111 fmt .Println (err )
125- w .WriteHeader (500 )
112+ w .WriteHeader (http . StatusInternalServerError )
126113 w .Write ([]byte ("Error creating temp file" ))
127114 return
128115 }
@@ -131,7 +118,7 @@ func uploadFile(w http.ResponseWriter, r *http.Request) {
131118
132119 if _ , err := io .CopyN (tempFile , file , fileSize ); err != nil {
133120 fmt .Println (err )
134- w .WriteHeader (500 )
121+ w .WriteHeader (http . StatusInternalServerError )
135122 w .Write ([]byte ("Error saving the file" ))
136123 return
137124 }
@@ -155,5 +142,5 @@ func uploadFile(w http.ResponseWriter, r *http.Request) {
155142
156143 // done
157144 fmt .Printf ("Successfully Uploaded File\n \n \n " )
158- http .Redirect (w , r , "/" , 302 )
145+ http .Redirect (w , r , "/" , http . StatusFound )
159146}
0 commit comments