Building Your First Web Server with Go

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up Go
  4. Creating the Web Server
  5. Handling Requests
  6. Creating a Response
  7. Running the Web Server
  8. Conclusion

Introduction

In this tutorial, we will learn how to build a simple web server using the Go programming language. By following this tutorial, you will understand the basics of creating a web server, handling HTTP requests, and sending HTTP responses. We’ll also cover how to set up Go on your machine and run the web server locally.

By the end of this tutorial, you will have a working web server that can respond to HTTP requests with custom messages or files. Let’s get started!

Prerequisites

Before starting this tutorial, you should have a basic understanding of Go programming language syntax and have Go installed on your machine. If you’re new to Go, it’s recommended to go through the official Go tutorial to familiarize yourself with the language.

Setting Up Go

  1. Download and install Go from the official Go website: https://golang.org/dl/

  2. Verify the installation by opening a terminal and running the following command:

    ```
    go version
    ```
    
    You should see the installed Go version printed on the screen.
    

Creating the Web Server

  1. Create a new directory for your web server project and navigate into it using the terminal.

  2. Inside the project directory, create a new file called main.go:

    ```
    touch main.go
    ```
    
  3. Open main.go in a text editor and add the following code:

    ```go
    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func main() {
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintf(w, "Hello, World!")
        })
    }
    ```
    
    Let's go through the code to understand what it does:
    
    - We import the necessary packages: `fmt` for formatting and printing, and `net/http` for creating and handling HTTP servers.
    - In the `main` function, we use `http.HandleFunc` to register a handler for the root ("/") URL pattern.
    - Inside the handler function, we use `fmt.Fprintf` to write the response "Hello, World!" to the `http.ResponseWriter` interface.
    

Handling Requests

Now that we have our web server set up, let’s enhance it to handle different types of requests.

  1. Inside the main function in main.go, add the following code below the existing fmt.Fprintf line:

    ```go
    http.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "This is the about page.")
    })
    
    http.HandleFunc("/contact", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "You can reach us at [email protected].")
    })
    ```
    
    In this code, we register two additional handlers for the "/about" and "/contact" URL patterns. Each handler responds with a different message.
    
  2. Save the main.go file.

Creating a Response

We’ve been using plain text responses so far. Let’s explore how to serve HTML files as responses.

  1. Create a new directory called templates inside the project directory.

    ```
    mkdir templates
    ```
    
  2. Inside the templates directory, create a file called index.html and add the following HTML code:

    ```html
    <!DOCTYPE html>
    <html>
    <head>
        <title>My Web Server</title>
    </head>
    <body>
        <h1>Welcome to my web server!</h1>
        <p>This is a simple web server built with Go.</p>
    </body>
    </html>
    ```
    
    This HTML file will be served as the response when a client accesses the root ("/") URL.
    
  3. Open main.go in a text editor and import the html/template package at the top of the file:

    ```go
    import (
        "fmt"
        "html/template"
        "net/http"
    )
    ```
    
  4. Inside the main function, add the following code below the existing handler definitions:

    ```go
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        tmpl, err := template.ParseFiles("templates/index.html")
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    
        err = tmpl.Execute(w, nil)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    })
    ```
    
    In this code, we use the `template.ParseFiles` function to parse the `index.html` template file. If there is any error during parsing, we return an HTTP 500 Internal Server Error response.
    
    We then use the `Execute` method of the parsed template to render it and write the output to the `http.ResponseWriter`.
    
  5. Save the main.go file.

Running the Web Server

Now that our web server is ready, let’s run it and see the results.

  1. Open a terminal and navigate to your project directory.

  2. Build and run the Go program using the following command:

    ```bash
    go run main.go
    ```
    
  3. The web server should now be running. Open a web browser and visit http://localhost:8000 to see the homepage.

    You should see the "Welcome to my web server!" message displayed in your browser.
    
  4. Visit http://localhost:8000/about and http://localhost:8000/contact to see the respective pages.

    You should see the custom messages for each page displayed.
    

    Congratulations! You have successfully built your first web server with Go. You now understand the basics of setting up a web server, handling different types of requests, and serving HTML files as responses.

Conclusion

In this tutorial, we learned how to create a basic web server using the Go programming language. We covered registering handlers for different URL patterns, creating responses with plain text and HTML, and running the web server locally.

With this knowledge, you can further explore Go’s extensive standard library and create more advanced web applications. Go provides powerful features for concurrent programming, database connectivity, and much more.

Feel free to experiment with the web server code we built and customize it to your needs. Happy coding!