Building Your First Web Server in Go
Go (Golang) is a powerful and efficient language for building backend systems, including web services. This module will guide you through setting up a basic web server using Go's built-in
net/http
Understanding the `net/http` Package
The
net/http
http.HandleFunc
http.ListenAndServe
A web server listens for incoming requests and responds to them.
At its core, a web server is a program that waits for clients (like web browsers) to send requests. When a request arrives, the server processes it and sends back a response, typically containing the requested data or an error message.
In the context of Go's net/http
package, this listening and responding mechanism is managed by the http.ListenAndServe
function. This function takes an address (like :8080
for port 8080) and a handler. The handler is responsible for processing incoming HTTP requests. When a request matches a registered path, the associated function is executed.
Writing Your First Go Web Server
Let's create a simple Go program that starts a web server. This server will respond with 'Hello, World!' to any request made to its root path (
/
The net/http
package.
Here's the code:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", helloHandler) // Register handler for the root path
fmt.Println("Starting server on :8080")
err := http.ListenAndServe(":8080", nil) // Start the server
if err != nil {
panic(err)
}
}
This code defines a helloHandler
function that writes 'Hello, World!' to the response writer. The main
function then registers this handler for the root path (/
) using http.HandleFunc
. Finally, http.ListenAndServe
starts the server on port 8080. The nil
argument for the handler means it will use the default ServeMux
, which is where http.HandleFunc
registers handlers.
Text-based content
Library pages focus on text content
Running Your Server
Save the code above as
main.go
go run main.go
You should see the message "Starting server on :8080". Now, open your web browser and go to
http://localhost:8080
The http.ListenAndServe
function blocks execution until the server is stopped or encounters an error. This is why the fmt.Println
message appears before the server starts listening.
Handling Different Routes
You can register multiple handlers for different URL paths. For example, to add a handler for
/about
Using http.HandleFunc("/your/path", yourHandlerFunction)
.
Here's how you'd add an
/about
Loading diagram...
Modify your
main.go
package mainimport ("fmt""net/http")func helloHandler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "Hello, World!")}func aboutHandler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "This is the about page.")}func main() {http.HandleFunc("/", helloHandler)http.HandleFunc("/about", aboutHandler)fmt.Println("Starting server on :8080")err := http.ListenAndServe(":8080", nil)if err != nil {panic(err)}}
Now, if you visit
http://localhost:8080/about
Learning Resources
The official Go documentation for the net/http package, providing comprehensive details on its functions and types.
A practical, hands-on tutorial demonstrating how to build HTTP servers and clients in Go with clear code examples.
A step-by-step guide to setting up a basic web server in Go, covering routing and request handling.
An excerpt or overview of a book focusing on Go's web capabilities, explaining fundamental HTTP concepts.
An in-depth explanation of Go's `http.HandlerFunc` and how it works within the `net/http` server.
The official Go language specification detailing the behavior and implementation of HTTP servers.
A video tutorial demonstrating the creation of a basic web server in Go, walking through the code line by line.
Another video resource that covers setting up an HTTP server in Go, often with practical examples and explanations.
The source code for Go's HTTP server implementation, useful for understanding the underlying mechanics.
A foundational explanation of the Hypertext Transfer Protocol (HTTP), essential for understanding web server operations.