LibrarySetting up a basic web server with the framework

Setting up a basic web server with the framework

Learn about Setting up a basic web server with the framework as part of Go Programming for Backend Systems

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

code
net/http
package, which is the standard library for handling HTTP requests and responses.

Understanding the `net/http` Package

The

code
net/http
package provides HTTP client and server implementations. For our purposes, we'll focus on the server-side capabilities. Key components include
code
http.HandleFunc
for registering handlers and
code
http.ListenAndServe
for starting the server.

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 (

code
/
).

What is the primary Go package used for building web servers?

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

code
main.go
. Open your terminal, navigate to the directory where you saved the file, and run it using:

code
go run main.go

You should see the message "Starting server on :8080". Now, open your web browser and go to

code
http://localhost:8080
. You will see the text 'Hello, World!' displayed.

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

code
/about
:

How do you register a handler for a specific URL path in Go?

Using http.HandleFunc("/your/path", yourHandlerFunction).

Here's how you'd add an

code
/about
route:

Loading diagram...

Modify your

code
main.go
like this:

go
package main
import (
"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

code
http://localhost:8080/about
, you'll see "This is the about page.".

Learning Resources

Go Docs: net/http Package(documentation)

The official Go documentation for the net/http package, providing comprehensive details on its functions and types.

Go by Example: HTTP Servers(tutorial)

A practical, hands-on tutorial demonstrating how to build HTTP servers and clients in Go with clear code examples.

Building a Web Server in Go(blog)

A step-by-step guide to setting up a basic web server in Go, covering routing and request handling.

Go Web Programming - Chapter 1: HTTP Basics(book)

An excerpt or overview of a book focusing on Go's web capabilities, explaining fundamental HTTP concepts.

Understanding Go's net/http Server(blog)

An in-depth explanation of Go's `http.HandlerFunc` and how it works within the `net/http` server.

Go Programming Language Specification: HTTP(documentation)

The official Go language specification detailing the behavior and implementation of HTTP servers.

Learn Go: Building a Simple Web Server(video)

A video tutorial demonstrating the creation of a basic web server in Go, walking through the code line by line.

Golang HTTP Server Tutorial(video)

Another video resource that covers setting up an HTTP server in Go, often with practical examples and explanations.

Go net/http Server Example(documentation)

The source code for Go's HTTP server implementation, useful for understanding the underlying mechanics.

What is HTTP?(wikipedia)

A foundational explanation of the Hypertext Transfer Protocol (HTTP), essential for understanding web server operations.