Skip to content

Instantly share code, notes, and snippets.

@anujsinghwd
Created March 16, 2018 10:47
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save anujsinghwd/a5b07db628012b99f875a431d081a490 to your computer and use it in GitHub Desktop.
Save anujsinghwd/a5b07db628012b99f875a431d081a490 to your computer and use it in GitHub Desktop.
Upload File - golang
package main
import (
"crypto/md5"
"fmt"
"io"
"net/http"
"os"
"strconv"
"text/template"
"time"
)
func main() {
http.HandleFunc("/upload", upload)
http.ListenAndServe(":8000", nil)
}
func upload(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
if r.Method == "GET" {
crutime := time.Now().Unix()
h := md5.New()
io.WriteString(h, strconv.FormatInt(crutime, 10))
token := fmt.Sprintf("%x", h.Sum(nil))
t, _ := template.ParseFiles("upload.gtpl")
t.Execute(w, token)
} else {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fmt.Fprintf(w, "%v", handler.Header)
f, err := os.OpenFile("./"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment