When developing web applications, one of the fundamental aspects is the management of data entered by users through forms. In Go programming language, this process can be tackled easily and effectively. In this article, well explore how to handle form submissions in Go using the standard
net/http
package.
Before starting, lets make sure we have Go installed on our system and a basic understanding of the syntax and fundamental concepts of the language.
Before we can handle form data submissions, we need to create the form page itself. To do this, we will create an HTML file containing the form with the necessary input fields. Lets save this file as
index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Form di esempio</title>
</head>
<body>
<h1>Compila il form</h1>
<form action="/submit" method="post">
<label for="name">Nome:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<input type="submit" value="Invia">
</form>
</body>
</html>
This form is quite simple and contains two input fields: "Name" and "Email". When sent, the data will be sent to the server via an HTTP POST request.
Now, lets create a Go server that will handle the form request and the data submitted by the users. Lets create a file called
main.go
and add the following code:
package main
import (
"fmt"
"net/http"
)
func formHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
// Otteniamo i dati del form dal campo "name" e "email"
name := r.FormValue("name")
email := r.FormValue("email")
// Puoi qui elaborare i dati inviati come preferisci,
// ad esempio, salvarli nel database o inviarli per email.
// Inviamo una risposta di conferma all'utente
fmt.Fprintf(w, "Grazie %s per aver inviato il form!\n", name)
fmt.Fprintf(w, "Hai inserito l'indirizzo email: %s\n", email)
} else {
// Se la richiesta non รจ di tipo POST, mostriamo il form
http.ServeFile(w, r, "index.html")
}
}
func main() {
http.HandleFunc("/", formHandler)
http.ListenAndServe(":8080", nil)
}
-
The
net/http
package is used to build the server and handle HTTP requests. -
The
formHandler
function is called whenever the server receives a request. If the request is of type POST, the form data is extracted and managed (in our case, simply printed for example purposes). If the request is not of type POST, the HTML form page is served. -
The
main
function starts the server listening on port 8080.
To run the application, open a terminal window, navigate to the folder where
main.go
is located, then run the following command:
go run main.go
Now if we visit
http://localhost:8080
in our browser we should see the form we created earlier. We fill in the form with the requested data and click on the "Send" button. We should see a confirmation page showing the data entered into the form.