Skip to content

Simple HTTP Server in Golang

In this article, we will create a simple HTTP server in Golang that listens on port 8080 and returns a Hello, World! message when a request is made to the root URL /.

Create a New Go Module

First, let’s create a new Go module by running the following command:

go mod init http-server

This command will create a new go.mod file in the current directory.

Create a New Go File

Next, create a new Go file named main.go with the following content:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Run the Server

Finally, run the server by executing the following command:

go run main.go

Now, open your browser and navigate to http://localhost:8080/. You should see a Hello, World! message displayed on the screen.

That’s it! You have successfully created a simple HTTP server in Golang. You can now modify the handler function to return different responses based on the request URL or method.