Golang is a statically typed, compiled programming language with a syntax similar to C. It was designed to be efficient, reliable, and easy to learn. Key features of Golang include:
net/http
.In web development, Golang can be used to build both the backend and, in some cases, the frontend of web applications. The net/http
package in the standard library provides a simple and powerful way to create HTTP servers and handle requests.
go version
The following is a basic example of a Golang web server:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
In this code:
handler
function is responsible for handling HTTP requests. It takes an http.ResponseWriter
and an http.Request
as parameters.http.HandleFunc
maps the root path (/
) to the handler
function.http.ListenAndServe
starts the HTTP server on port 8080.To run the server, save the code in a file named main.go
and run the following command in the terminal:
go run main.go
Then, open your web browser and navigate to http://localhost:8080
. You should see the message “Hello, World!”.
Golang can handle different HTTP request methods such as GET, POST, PUT, DELETE, etc. The following example shows how to handle a GET request:
package main
import (
"fmt"
"net/http"
)
func getHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
fmt.Fprintf(w, "This is a GET request.")
}
}
func main() {
http.HandleFunc("/get", getHandler)
http.ListenAndServe(":8080", nil)
}
You can set response headers and status codes using the http.ResponseWriter
interface.
package main
import (
"net/http"
)
func customResponseHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content - Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte("Custom response"))
}
func main() {
http.HandleFunc("/custom", customResponseHandler)
http.ListenAndServe(":8080", nil)
}
While the standard library provides basic routing capabilities, for more complex routing requirements, you can use third - party libraries like gorilla/mux
.
gorilla/mux
go get -u github.com/gorilla/mux
gorilla/mux
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the home page!")
}
func userHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
user := vars["user"]
fmt.Fprintf(w, "Hello, %s!", user)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", homeHandler)
r.HandleFunc("/users/{user}", userHandler)
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
In this example, the gorilla/mux
router allows us to define routes with variables, such as the {user}
variable in the /users/{user}
route.
Golang has a built - in html/template
package for working with HTML templates.
First, create an HTML template file named index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
<title>Template Example</title>
</head>
<body>
<h1>Hello, {{.Name}}!</h1>
</body>
</html>
Then, the following Golang code uses the template:
package main
import (
"html/template"
"net/http"
)
func templateHandler(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("index.html"))
data := struct{ Name string }{Name: "John"}
tmpl.Execute(w, data)
}
func main() {
http.HandleFunc("/template", templateHandler)
http.ListenAndServe(":8080", nil)
}
In this code, we parse the index.html
template file and execute it with some data.
Golang can integrate with various databases. Here is an example of integrating with a MySQL database using the go - sql - driver/mysql
package.
go get -u github.com/go-sql-driver/mysql
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname")
if err != nil {
log.Fatal(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT id, name FROM users")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name string
err = rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
fmt.Printf("ID: %d, Name: %s\n", id, name)
}
if err = rows.Err(); err != nil {
log.Fatal(err)
}
}
This code connects to a MySQL database, queries the users
table, and prints the results.
In this tutorial, we have covered the fundamental concepts, usage methods, common practices, and best practices of using Golang for web development. Golang’s simplicity, performance, and concurrency features make it a great choice for building web applications. By following the examples and best practices outlined in this tutorial, you can start building your own web applications with Golang.