Skip to content

Instantly share code, notes, and snippets.

@pog5
Created September 26, 2023 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pog5/12920615a49002db49558595c79703d1 to your computer and use it in GitHub Desktop.
Save pog5/12920615a49002db49558595c79703d1 to your computer and use it in GitHub Desktop.
Basic HTTP File Upload server written in Go without JavaScript, saving files as their MD5 hash + extention (if it exists)
package main
import (
"crypto/md5"
"encoding/hex"
"io"
"net/http"
"os"
"strings"
)
func main() {
os.Mkdir("uploads", 0777)
http.HandleFunc("/", handle)
if err := http.ListenAndServe(":80", nil); err != nil {
panic(err)
}
}
func handle(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
r.ParseMultipartForm(100000)
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
hash := md5.New()
io.Copy(hash, file)
hashString := hex.EncodeToString(hash.Sum(nil))
if strings.Contains(handler.Filename, ".") {
hashString = hashString + handler.Filename[strings.LastIndex(handler.Filename, "."):len(handler.Filename)]
}
f, _ := os.Create("uploads/" + hashString)
defer f.Close()
file.Seek(0, 0)
io.Copy(f, file)
w.WriteHeader(http.StatusCreated)
w.Write([]byte("<a href=\"" + hashString + "\">" + hashString + "</a>"))
return
}
if r.URL.Path != "/" {
if _, err := os.Stat("uploads/" + r.URL.Path[1:len(r.URL.Path)]); err == nil {
http.ServeFile(w, r, "uploads/"+r.URL.Path[1:len(r.URL.Path)])
return
}
http.Error(w, "404 Not Found", http.StatusNotFound)
return
}
w.Write([]byte("<p><form enctype=\"multipart/form-data\" method=\"post\"><input type=\"file\" name=\"file\"/><input type=\"submit\"/></form>"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment