Creating a Simple HTTP Server in Golang

Golang HTTP Server

A Simple HTTP Server in Golang can easily be created using Golang’s net/http package.

In this blog, we will be creating a simple HTTP Server in Golang that will render some text on the browser.

Create a http-server.go file and copy the code.

Golang HTTP Server

// Golang HTTP Server
package main

import (
	"fmt"
	"log"
	"net/http"
)

const (
	// Host name of the HTTP Server
	Host = "localhost"
	// Port of the HTTP Server
	Port = "8080"
)

func home(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "This is a Simple HTTP Web Server!")
}

func main() {
	http.HandleFunc("/", home)
	err := http.ListenAndServe(Host+":"+Port, nil)
	if err != nil {
		log.Fatal("Error Starting the HTTP Server : ", err)
		return
	}

}

Run the program from the command line.

$  go run http-server.go

After running the program, an HTTP server will start locally on port 8080.

Open http://localhost:8080 in a browser and the text will be rendered on the browser from the server.

Screenshot of the browser.

golang HTTP Server
Golang HTTP Server

Understanding HTTP Server in GO

The first line of the http-server.go file is package main that defines the package name of the program. After that we import the needed packages for the HTTP server in Go.

const ( .... ) In Const Block we define some of the constants for the program. One constant variable is the Hostname and the second one is the port number.

The home() function takes a ResponseWriter and a pointer to the Request as input and implements the Handler interface, and writes some text on the server using Fprint Function.

Main Function

The program starts executing from the main() function. It is the entry point for every Go program.

The HandleFunc() function in http-server.go’s the main function registers the home() function that implements the handler interface to the path “/”.

Due to this home() function gets executed whenever we visit the “/” path.

Next, we call the ListenAndServer() function that accepts the “Host: Port” as a string and the handler. In this case, we are using the default handler that’s why we use nil.

After that, we check for any kind of error from the ListenAndServer() function. If there is, then we log the error and exit with a status code of 1.

Learn more about Golang HTTP Server form the net/http package.

Choose your next topic to learn from the Golang Command Line Argument.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *