Created
January 7, 2015 19:34
-
-
Save bensie/cdecd79cbcfb3ecf0ddb to your computer and use it in GitHub Desktop.
Quick and dirty golang file uploader
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 ( | |
"fmt" | |
"io" | |
"net/http" | |
"os" | |
) | |
func uploadHandler(w http.ResponseWriter, r *http.Request) { | |
file, header, err := r.FormFile("file") | |
if err != nil { | |
fmt.Fprintln(w, err) | |
return | |
} | |
defer file.Close() | |
out, err := os.Create("./uploads/" + header.Filename) | |
if err != nil { | |
fmt.Fprintf(w, "Unable to create the file for writing.") | |
return | |
} | |
defer out.Close() | |
_, err = io.Copy(out, file) | |
if err != nil { | |
fmt.Fprintln(w, err) | |
} | |
fmt.Fprintf(w, "File uploaded successfully : ") | |
fmt.Fprintf(w, header.Filename) | |
} | |
func main() { | |
http.HandleFunc("/", uploadHandler) | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment