Go, also known as Golang, makes it incredibly easy to set up a simple HTTP server with just a few lines of code. In this article, we will walk through building a basic HTTP server in under 2 minutes.

Setup Your Go Environment

Ensure you have Go installed on your machine. You can download it from the official Go downloads page. Once installed, verify by running the following command:

go version

Create Your Go Server File

Start by creating a new directory where your project files will reside. Inside this directory, create a file named main.go:

mkdir go-http-server
cd go-http-server
touch main.go

Write Your Go HTTP Server Code

Edit the main.go file and add the following 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)
    fmt.Println("Starting server at port 8080...")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

Run Your HTTP Server

To start the server, open your terminal, navigate to the project directory, and run:

go run main.go

Your server is now running on localhost at port 8080. You can visit http://localhost:8080 in your web browser to see the message "Hello, World!" displayed.

Understanding the Code

The Go code above does the following:

  • import "net/http": This brings in Go's net/http package which provides HTTP client and server implementations.
  • helloHandler: This function handles HTTP requests. When invoked, it writes a simple "Hello, World!" response.
  • http.HandleFunc("/", helloHandler): This sets up a route at / to use the helloHandler function whenever a request is made to this path.
  • http.ListenAndServe(":8080", nil): This starts the server on port 8080.

That's all you need to create a basic HTTP server in Go. You can now extend this server by adding more routes and handlers as needed for more complex applications.