Golang : Get checkbox or extract multipart form data value example
This tutorial is a slight modification on the previous tutorial on the how to upload multiple files and this time we will learn how to get the values of a multi-part form data.
To extract the values from a multi-part form is easy after parsing with ParseMultipartForm()
and with request.FormValue()
The example below will show you how to get the value of a checkbox. Run this code, point your browser to your web server port 8080 and you should see a simple form. Click on the check box and press submit button. Rerun the process again but this time WITHOUT ticking the check box.
Here you go!
package main
import (
"fmt"
"net/http"
)
func Home(w http.ResponseWriter, r *http.Request) {
html := `<html>
<title>Go upload</title>
<body>
<form action="http://example.com:8080/getcheckbox" method="post" enctype="multipart/form-data">
<label for="file">Filenames:</label>
<input type="file" name="multiplefiles" id="multiplefiles" multiple>
<input type="checkbox" name="compress" value="compressboxchecked">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>`
//output to web browser(client)
w.Write([]byte(fmt.Sprintf(html)))
}
func GetCheckBox(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(200000) // grab the multipart form
if err != nil {
fmt.Fprintln(w, err)
return
}
// get the value of checkbox
// if the checkbox is not ticked, the value will be empty
fmt.Fprintln(w, r.FormValue("compress"))
fmt.Println("Compress the file ? : ", r.FormValue("compress"))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", Home)
mux.HandleFunc("/getcheckbox", GetCheckBox)
http.ListenAndServe(":8080", mux)
}
SEE ALSO :
https://www.socketloop.com/tutorials/upload-multiple-files-golang
See also : Upload multiple files with Go
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+17.6k Golang : Get all upper case or lower case characters from string example
+14.8k Golang : How do I get the local IP (non-loopback) address ?
+14.1k Golang : Send email with attachment(RFC2822) using Gmail API example
+10.2k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+29.9k Golang : How to verify uploaded file is image or allowed file types
+8.3k Golang : Another camera capture GUI application with GTK and OpenCV
+5.2k Golang *File points to a file or directory ?
+9.4k Golang : interface - when and where to use examples
+39.6k Golang : Convert to io.ReadSeeker type
+8.2k Android Studio : Import third-party library or package into Gradle Scripts
+5.9k Golang : How to write backslash in string?
+6.4k Golang : Skip or discard items of non-interest when iterating example