Example to handle GET and POST request in Golang

ParseForm populates r.Form and r.PostForm.
For all requests, ParseForm parses the raw query from the URL and updates r.Form.

User submitted form details storing in 2 variables name and address.
The HTML form have 2 input box of name and address.
Create two different files form.html and main.go
<!DOCTYPE html>
  <meta charset="UTF-8" />
  <form method="POST" action="/">     
      <label>Name</label><input name="name" type="text" value="" />
      <label>Address</label><input name="address" type="text" value="" />
      <input type="submit" value="submit" />
package main

import (
func hello(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.Error(w, "404 not found.", http.StatusNotFound)

	switch r.Method {
	case "GET":		
		 http.ServeFile(w, r, "form.html")
	case "POST":
		// Call ParseForm() to parse the raw query and update r.PostForm and r.Form.
		if err := r.ParseForm(); err != nil {
			fmt.Fprintf(w, "ParseForm() err: %v", err)
		fmt.Fprintf(w, "Post from website! r.PostFrom = %v\n", r.PostForm)
		name := r.FormValue("name")
		address := r.FormValue("address")
		fmt.Fprintf(w, "Name = %s\n", name)
		fmt.Fprintf(w, "Address = %s\n", address)
		fmt.Fprintf(w, "Sorry, only GET and POST methods are supported.")

func main() {
	http.HandleFunc("/", hello)

	fmt.Printf("Starting server for testing HTTP POST...\n")
	if err := http.ListenAndServe(":8080", nil); err != nil {
You need to run main.go and then in browser.
Run url http://localhost:8080/ in your browser and see the below content

After submit the form

Thanks for reading. Please leave your valuable feedback and comments.

* Required Fields

Questions: It's actually a great and helpful piece of information. I am glad that you just shared this useful information with us. Please stay us up to date like this. Thank you for sharing. dedbeecedbdc
Question By: Johnb296 on Feb 5 2018 5:51 AM