Advertisement

In this blog, we will learn about the Golang TCP and how we can build Go HTTP (Hypertext transfer protocol) Server using TCP (Transmission Control Protocol) from the Golang Net Package.

To use Golang TCP and related functions we are going to use the Net Package.

import “net”

Golang HTTP is built over TCP, as the import implies:

import “net/http”

TCP i.e Transmission Control Protocol is the transport layer from the OSI Network layer.

HTTP built over TCP is a set of protocols designed by IETF (Internet Engineering Task Force) that describes the Request-Response Architecture.

Golang TCP – net.Listen

First, we will learn to make Golang TCP Server in order to work with HTTP.

The Golang Net Package has net.Listen function that takes the name of connection type and the required port and enables us to make a TCP Server.

listen, err := net.Listen("tcp", ":8080")

Next, we check for any kind of error from the net.Listen and print it.

Types of Errors might be that the port is occupied or unable to connect.

if err != nil {
	log.Fatalln(err.Error())
}

Then, we use the deferred close statement that closes the connection and thus the resource (port) is taken from the program.

defer listen.Close()

After handling all kinds of errors and closing the connection, it’s time to accept the connection. We will use an infinite loop that will accept the connection and handle the connection.

for {
	conn, err := listen.Accept()
	if err != nil {
		log.Fatalln(err.Error())
	}
	go handleConnection(conn)
}

Golang HTTP using TCP

As we know, HTTP is a set of Protocols about the Request-Response Architecture.

We will also have to create Request and Response Functions.

Both Request and Response functions will be called in the handleConnection function.

func handleConnection(conn net.Conn) {
	defer conn.Close()
	request(conn)
	response(conn)
}

Golang HTTP Request

This Function handles the requests from the user.

In this function, we scan through the request data and fetch the type of method the connection is asking for.

func request(conn net.Conn) {
	i := 0
	scanner := bufio.NewScanner(conn)
	for scanner.Scan() {
		line := scanner.Text()
		if i == 0 {
			m := strings.Fields(line)[0]
			fmt.Println("Methods", m)
		}
		if line == "" {
			break
		}
		i++
	}
}

Golang HTTP Response

HTTP Response is processed in the response function and the processed data then is written into the connection.

func response(conn net.Conn) {
	body := `

This is Go Http Server using TCP

`

	fmt.Fprint(conn, "HTTP/1.1 200 OK\r\n")
	fmt.Fprintf(conn, "Content-Length: %d\r\n", len(body))
	fmt.Fprint(conn, "Content-Type: text/html\r\n")
	fmt.Fprint(conn, "\r\n")
	fmt.Fprint(conn, body)
}

Golang HTTP Server Image

Run the following Go program and then Open the web browser and go to localhost:8080 and you will see this.

When you go to localhost:8080 the browser requests for data from the TCP layer and the connection is then passed to the request function.

After returning from the request function the connection is passed to the response function and the data is then written onto the connection.

Golang HTTP Server Using TCP Code

package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"strings"
)

func main() {

	listen, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalln(err.Error())
	}
	defer listen.Close()

	for {
		conn, err := listen.Accept()
		if err != nil {
			log.Fatalln(err.Error())
		}
		go handleConnection(conn)
	}

}

func handleConnection(conn net.Conn) {
	defer conn.Close()
	request(conn)
	response(conn)
}

func request(conn net.Conn) {
	i := 0
	scanner := bufio.NewScanner(conn)
	for scanner.Scan() {
		line := scanner.Text()
		if i == 0 {
			m := strings.Fields(line)[0]
			fmt.Println("Methods", m)
		}
		if line == "" {
			break
		}
		i++
	}
}

func response(conn net.Conn) {
	body := `

This is Go Http Server using TCP

`

	fmt.Fprint(conn, "HTTP/1.1 200 OK\r\n")
	fmt.Fprintf(conn, "Content-Length: %d\r\n", len(body))
	fmt.Fprint(conn, "Content-Type: text/html\r\n")
	fmt.Fprint(conn, "\r\n")
	fmt.Fprint(conn, body)
}

Hope you like it!

Also, read Why Golang is called the future of Server-side language?

Learn more about Golang Net Package from the official Documentation.

About Author
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top