Post

Go request.FormValue("xyz")

How to use request.FormValue in Go to retrieve form data submitted via POST and GET methods.

This example shows how to use r.FormValue() in Go to extract query parameters and form data from HTTP requests. The handler function creates an HTML page with two forms: one using POST and one using GET, demonstrating both submission methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {

	http.HandleFunc("/", index)

	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.ListenAndServe(":8080", nil)
}

func index(w http.ResponseWriter, r *http.Request) {
	user := r.FormValue("user")
	surname := r.FormValue("surname")
	w.Header().Set("Content-type", "text/html")

	fmt.Printf("requested url: %v\n", r.URL)
	fmt.Printf("input variable user: %v\n", user)
	// io.WriteString(w, "Hello from Go dude! Username: " + v + "\n")

	io.WriteString(w, `
	<p>Now the form requires POST (user)</p>
	<form method="post">
		<input type="text" name="user">
		<input type="submit">
	</form>
	` + user + `<p>Now the form requires GET (surname)</p>
	<form method="get">
	<input type="text" name="surname">
	<input type="submit">
	</form>` + surname)
}

This post is licensed under CC BY 4.0 by the author.