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> <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>
Example
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)
}
}
Run url
http://localhost:8080/
in your browser and see the below contentAfter submit the form
Most Helpful This Week
Regular expression to extract filename from given path in Golang
How to import and alias package names?
Get Hours, Days, Minutes and Seconds difference between two dates [Future and Past]
Select single argument from all arguments of variadic function
How to add and update elements in Map?
Converting Int data type to Float in Go
Print index and element or data from Array, Slice and Map
How to read input from console line?
Regular expression to extract numbers from a string in Golang
How to check string contains uppercase lowercase character in Golang?