Developer Guides

Go tutorial for beginners: Build a Golang HTTP server

Learn how to build an HTTP server in Golang with a straightforward guide for beginners.

3 min read

Learn step-by-step how to build a simple yet functional HTTP server in Golang using only the standard library. This beginner-friendly guide will walk you through setting up a project, structuring your application, and running a basic HTTP server.

Prerequisites

Before starting, ensure you have the following:

prerequisites

  • Go Programming Language: Installed on your system. Download it from the official Go installation page and verify it with go version.
  • Basic Programming Knowledge: Familiarity with concepts like functions, variables, and conditionals.
  • Command-Line Basics: Comfort navigating directories and running commands in a terminal.

Set Up the Environment

Initialize the project and prepare the directory structure.

steps

  1. Create a new folder and navigate to it:

    bash
    mkdir go_http_server
    cd go_http_server
  2. Initialize a Go module:

    bash
    go mod init go_http_server

    This creates a go.mod file that defines your module and tracks dependencies.

  3. Verify the setup:

    • Ensure go.mod is created within your folder.
    • Check the Go version with:
      bash
      go version

Create and Structure the Application

Use a standard Go project layout to keep the code organized.

file tree

go_http_server/
├── cmd/
│   └── server/
│       └── main.go
└── go.mod
  • cmd/server/main.go: This will hold the entry point for running the HTTP server.

Building the HTTP Server

We'll now create a minimal HTTP server using the net/http package.

steps

  1. Navigate to the cmd/server directory:

    bash
    cd cmd/server
  2. Create and edit main.go:

    bash
    nano main.go
  3. Start with the following Go code:

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    // handler function that responds to HTTP requests
    func helloHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    }
    
    func main() {
        // Register the handler function to an endpoint
        http.HandleFunc("/", helloHandler)
    
        // Start the HTTP server on port 8080
        fmt.Println("Starting server on :8080")
        if err := http.ListenAndServe(":8080", nil); err != nil {
            fmt.Println("Error starting server:", err)
        }
    }
    • This code defines a helloHandler function for responding with "Hello, World!" and starts the server on port 8080.
  4. Run the server:

    bash
    go run main.go
  5. Verify the server:

    • Open a browser and navigate to http://localhost:8080.
    • You should see Hello, World! displayed.

Verifying the Server Setup

Debug your server and ensure the setup is functional.

Tips for Beginners


FAQ

Can I use HTTPS with this HTTP server?

Yes, you can use http.ListenAndServeTLS to serve HTTPS requests by providing a certificate and private key.

How do I add more endpoints?

Register more handlers by calling http.HandleFunc with different paths and handler functions.

What is the difference between http.Handle and http.HandleFunc?

http.HandleFunc simplifies registering handlers by accepting a standard function signature, while http.Handle works with objects implementing the http.Handler interface.


Official reference: Go documentation.