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)
}
}
Deprecated: Array and string offset access syntax with curly braces is deprecated in /home/golayrva/public_html/lib/Varien/Filter/Template/Tokenizer/Abstract.php on line 89
You need to run main.go and then in browser.
Run url
http://localhost:8080/
in your browser and see the below contentAfter submit the form
Most Helpful This Week
How to rotate an image?
How to verify a string only contains letters, numbers, underscores, and dashes in Golang?
Golang download image from given URL
Golang HTML parser
How to play and pause execution of goroutine?
How to check if a string contains only letters in Golang?
How to Unmarshal nested JSON structure?
How to add Watermark or Merge two image?
How to read/write from/to file in Golang?
How to declare and access pointer variable?