In this section, we will learn how to build a simple web server using Go. This will involve setting up a basic HTTP server, handling requests, and sending responses. By the end of this section, you will have a foundational understanding of how to create web servers in Go.

Key Concepts

  1. HTTP Package: Go's net/http package provides the necessary tools to create web servers.
  2. Handlers: Functions that handle HTTP requests.
  3. Routing: Directing incoming requests to the appropriate handler functions.
  4. Response Writing: Sending responses back to the client.

Step-by-Step Guide

  1. Setting Up the Project

First, create a new directory for your project and navigate into it:

mkdir simple-web-server
cd simple-web-server

Initialize a new Go module:

go mod init simple-web-server

  1. Writing the Main Program

Create a new file named main.go and open it in your favorite text editor. Add the following code:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/about", aboutHandler)

	fmt.Println("Starting server at port 8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Println("Error starting server:", err)
	}
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome to the Home Page!")
}

func aboutHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "This is the About Page.")
}

  1. Explanation of the Code

  • Importing Packages: We import the fmt and net/http packages. fmt is used for formatted I/O, and net/http provides HTTP client and server implementations.
  • Main Function:
    • http.HandleFunc("/", homeHandler): This line registers the homeHandler function to handle requests to the root URL (/).
    • http.HandleFunc("/about", aboutHandler): This line registers the aboutHandler function to handle requests to the /about URL.
    • http.ListenAndServe(":8080", nil): This function starts the HTTP server on port 8080. If an error occurs, it prints the error message.
  • Handler Functions:
    • homeHandler: This function writes "Welcome to the Home Page!" to the response.
    • aboutHandler: This function writes "This is the About Page." to the response.

  1. Running the Server

To run the server, execute the following command in your terminal:

go run main.go

You should see the message "Starting server at port 8080". Open your web browser and navigate to http://localhost:8080 to see the home page and http://localhost:8080/about to see the about page.

  1. Practical Exercises

Exercise 1: Add a Contact Page

  1. Task: Add a new handler for a contact page at the URL /contact.
  2. Solution:
func contactHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "This is the Contact Page.")
}

func main() {
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/about", aboutHandler)
	http.HandleFunc("/contact", contactHandler)

	fmt.Println("Starting server at port 8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Println("Error starting server:", err)
	}
}

Exercise 2: Handle 404 Errors

  1. Task: Create a custom 404 error page.
  2. Solution:
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprintf(w, "404 - Page Not Found")
}

func main() {
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/about", aboutHandler)
	http.HandleFunc("/contact", contactHandler)

	http.HandleFunc("/", notFoundHandler)

	fmt.Println("Starting server at port 8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Println("Error starting server:", err)
	}
}

Common Mistakes and Tips

  • Port Already in Use: If you get an error that the port is already in use, make sure no other application is using port 8080 or change the port number.
  • Handler Function Signature: Ensure your handler functions have the correct signature: func(w http.ResponseWriter, r *http.Request).
  • Order of Handlers: The order in which you register handlers matters. Make sure to register specific routes before more general ones.

Conclusion

In this section, we covered the basics of building a simple web server in Go. We learned how to set up an HTTP server, create handler functions, and route requests. These foundational skills will be essential as we move on to more advanced topics in web development with Go.

© Copyright 2024. All rights reserved