Golang net/http.Request.FormFile() and FormValue() functions example

package net/http

Golang net/http.Request.FormFile() and FormValue() functions usage example

 func uploadHandler(w http.ResponseWriter, r *http.Request) {

  // the FormFile function takes in the POST input id file
  file, header, err := r.FormFile("file") // <-------------------------------- here!

  if err != nil {
 fmt.Fprintln(w, err)
 return
  }

  defer file.Close()

  out, err := os.Create("/tmp/uploadedfile")
  if err != nil {
 fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege")
 return
  }

  defer out.Close()

  // write the content from POST to the file
  _, err = io.Copy(out, file)
  if err != nil {
 fmt.Fprintln(w, err)
  }

  fmt.Fprintf(w, "File uploaded successfully : ")
  fmt.Fprintf(w, header.Filename)
 }

and

  func process_form_data(w http.ResponseWriter, r *http.Request)  {
 if r.Method == "POST" {
 form_data := r.FormValue("form_data")
 }
  }

References :

https://www.socketloop.com/tutorials/get-form-post-value-go

http://golang.org/pkg/net/http/#Request.FormFile

http://golang.org/pkg/net/http/#Request.FormValue

https://www.socketloop.com/tutorials/golang-upload-file

Advertisement