Create a Web Application with Go
Go is used for creating various applications including web applications (Dynamic content and HTTP server). In this tutorial we will use Golang to create a web application from scratch.
Prerequisites
To follow this tutorial, you will need to have Go installed on your computer and set up your workspace by following the instructions in this tutorial - Go installation and environment setup.
Import the necessary packages in Go
The first step in building a web application in Go is to import the necessary packages. You will need to import the "net/http" package, which provides functions for creating HTTP servers and clients, and the "html/template" package, which provides functions for generating HTML templates in Go.
To import these packages, add the following lines (or code block) to the beginning of the source file:
import (
"html/template"
"net/http"
)
Define your web app's routes and handler functions in Go
Next, you'll need to define paths for your application and corresponding controller functions. A route is a combination of an HTTP method (such as GET, PUT or POST) and a URL pattern that the application must respond to.
To define a route, you'll use the http.HandleFunc
function, which requires a pattern and a handler function as arguments. For instance:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Add handler code here
})
This will define a path that responds to GET requests at the URL "/". The controller function will receive two arguments: a ResponseWriter interface, used to write the response to the client, and a Request structure, which contains information about the request made by the client.
Write controller functions in Go
Next, you'll need to write controller functions for your application's paths. These functions will be in charge of performing the appropriate actions for each path and returning a response to the client. For example, if you're building a server that displays a list of users, you might have a controller function that queries a database for the list of users and then renders an HTML template with the list of users.
To render an HTML template, you must first parse the template file using the template.ParseFiles
function:
tmpl, err := template.ParseFiles("template.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
You can then define the data you want to pass to the model and run the model with that data:
data := struct {
Title string
Users []User
}{
Title: "Users",
Users: []User{
{Name: "Albert", Age: 50},
{Name: "Bobbin", Age: 32},
{Name: "Cooper", Age: 45},
},
}
err = tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
Start the HTTP server in Go
Finally, you can start the HTTP server using the http.ListenAndServe function, which takes an address and a controller as arguments. For instance:
http.ListenAndServe(":8080", nil)
Write the HTML template in Golang
The HTML template is the file that contains the layout and content of the application pages. You can include placeholders for dynamic data that controller functions will pass to it. For example, here's a simple HTML template displaying a list of users:
<html>
<head>
<title>{{.Title}}</title>
</head>
<body>
<h1>{{.Title}}</h1>
<ul>
{{range .Users}}
<li>{{.Name}} ({{.Age}} years old)</li>
{{end}}
</ul>
</body>
</html>
This template defines a layout with a title and a list of users. Use the range action to scroll through the list of users and view each user's name and age.
Access the web application written in Go
After completing your Golang script for web application, you need to save it (with the name main.go
)
package main
import (
"html/template"
"net/http"
"strconv"
)
type User struct {
Name string
Age int
}
var users []User
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Parse the HTML template
tmpl, err := template.ParseFiles("index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Define the data for the template
data := struct {
Title string
Users []User
}{
Title: "Users",
Users: users,
}
// Render the template with the data
err = tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
http.HandleFunc("/add", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
// Parse the form values
name := r.FormValue("name")
ageStr := r.FormValue("age")
age, err := strconv.Atoi(ageStr)
if err != nil {
http.Error(w, "Invalid age", http.StatusBadRequest)
return
}
// Add the user to the list of users
users = append(users, User{Name: name, Age: age})
// Redirect the user back to the homepage
http.Redirect(w, r, "/", http.StatusSeeOther)
}
})
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.ListenAndServe(":8080", nil)
}
Also save the HTML tempelate in index.html
file.
<html>
<head>
<title>{{.Title}}</title>
</head>
<body>
<h1>{{.Title}}</h1>
<ul>
{{range .Users}}
<li>{{.Name}} ({{.Age}} years old)</li>
{{end}}
</ul>
<form action="/add" method="post">
<label>Name: <input type="text" name="name"></label>
<br>
<label>Age: <input type="number" name="age"></label>
<br>
<input type="submit" value="Add user">
</form>
</body>
</html>
Now you need to run the script by executing these commands in terminal shell:
go run main.go
To access the web application, you will need to open a web browser and navigate to the server address. For example, if the server is running on port 8080 of the local computer, it can be accessed at http://localhost:8080.
Conclusion
In this tutorial, you learned how to build a web application in Go from scratch. You learned how to import the necessary packages, define controller paths and functions, generate HTML templates, and start the HTTP server.