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 same form name we had used in html form.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <div> <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" /> </form> </div> </body> </html>
package main
import (
	"fmt"
	"log"
	"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.Error(w, "404 not found.", http.StatusNotFound)
		return
	}
	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)
			return
		}
		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)
	default:
		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 {
		log.Fatal(err)
	}
}
Now 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

No questions yet. Be the first to ask the question!