Created
March 20, 2024 18:58
-
-
Save yashsinghcodes/6fdbfc3edf589caf514308de6a45a5de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/md5" | |
"encoding/hex" | |
"fmt" | |
"io" | |
"log" | |
"mime/multipart" | |
"net/http" | |
"os" | |
) | |
const ( | |
PORT = 8080 | |
) | |
type FileCreator interface { | |
HashFileName(name string, size int64) string | |
WriteFile(multipart.File, *multipart.FileHeader, string) error | |
} | |
type SimpleFileCreation struct{} | |
func (s SimpleFileCreation) HashFileName(name string, size int64) string { | |
key := name + fmt.Sprint(size) | |
h := md5.New() | |
h.Write([]byte(key)) | |
return hex.EncodeToString(h.Sum(nil)) | |
} | |
func (s SimpleFileCreation) WriteFile(file multipart.File, header *multipart.FileHeader, path string) error { | |
filename := path + s.HashFileName(header.Filename, header.Size) | |
dst, err := os.Create(filename) | |
if err != nil { | |
return err | |
} | |
defer dst.Close() | |
// TODO1 | |
_, err = io.Copy(dst, file) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
type FileHandler struct { | |
path string | |
ServerFileHandler FileCreator | |
} | |
func NewFileHandler() *FileHandler { | |
return &FileHandler{ | |
path: "/tmp/", | |
ServerFileHandler: SimpleFileCreation{}, | |
} | |
} | |
// TODO: Maybe a condition for data loss by checking if written bytes equal to uploaded byte -- GOTO TODO1 | |
func (h *FileHandler) handelFile(w http.ResponseWriter, r *http.Request) { | |
if r.Method != "POST" { | |
http.Error(w, "ONLY POST METHOD IS ALLOWED", http.StatusBadRequest) | |
return | |
} | |
file, header, err := r.FormFile("file") | |
if err != nil { | |
http.Error(w, "ERROR READING FILE", http.StatusBadRequest) | |
} | |
defer file.Close() | |
log.Printf("Writing file %s to server\n", header.Filename) | |
err = h.ServerFileHandler.WriteFile(file, header, h.path) | |
if err != nil { | |
http.Error(w, "ERROR SAVING FILE: "+err.Error(), http.StatusInternalServerError) | |
} | |
w.WriteHeader(http.StatusOK) | |
w.Write([]byte("File uploaded succesfully")) | |
} | |
func main() { | |
h := NewFileHandler() | |
http.HandleFunc("/upload", h.handelFile) | |
log.Printf("String the server at %d\n", PORT) | |
if err := http.ListenAndServe(fmt.Sprintf(":%d", PORT), nil); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment