Golang: Simple File Upload Using Go Languange

Free $20 Linode Cloud hosting Coupon, register at  Free Linode Cloud Hosting

(Coupon $20 available at Linode $.20 Coupon ) 👍🏿

As a web programming language Go has capability to handle file upload from browser html form, in this post I will show you simple File Upload using Golang web programming.

  1. Create HTML Form upload src/webupload/upload.gtpl
             <title>Test Upload a File</title>
    <form enctype="multipart/form-data" action="" method="post">
              {{/* 1. File input */}}
              <input type="file" name="uploadfile" />
              {{/* 2. Submit button */}}
              <input type="submit" value="upload file" />

    1. GO Form
    *ignore unused token input
  2. Create go code to handle file upload src/webupload/upload.go
  3. package main
    import (
    func upload(w http.ResponseWriter, r *http.Request) {
    	if r.Method == "GET" {
    		// GET
    		t, _ := template.ParseFiles("upload.gtpl")
    		t.Execute(w, nil)
    	} else if r.Method == "POST" {
    		// Post
    		file, handler, err := r.FormFile("uploadfile")
    		if err != nil {
    		defer file.Close()
    		fmt.Fprintf(w, "%v", handler.Header)
    		f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
    		if err != nil {
    		defer f.Close()
    		io.Copy(f, file)
    	} else {
    		fmt.Println("Unknown HTTP " + r.Method + "  Method")
    func main() {
    	http.HandleFunc("/upload", upload)
    	http.ListenAndServe(":9090", nil) // setting listening port
  4. Create new folder for upload destination src/webupload/testfolder
  5. that’s all


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s