Send a Request in Golang

One of the notable features of the Go language is its adeptness in handling network services enabling the sending of requests to resources on the network and seamlessly processing incoming requests. The primary tool for network functionality is encapsulated in the net package, which furnishes various low-level network primitives pivotal for communication.

Sending Requests

For dispatching requests to network resources, the Dial function is used like this:

func Dial(network, address string) (Conn, error)

This function necessitates two parameters: network, denoting the protocol type, and address, representing the resource address.

The following protocol types are supported:

tcp, tcp4, tcp6: TCP. tcp signifies tcp4 by default, with an appended number indicating the address type: IPv4 or IPv6.

The second parameter, address, embodies the network address of the resource. This can be a numeric network address or may include a specified port, such as:

Numeric address: "192.234.12.1"
Address with port: "192.234.12.1:80"
IPv6 address: "::1"

The Dial function returns an object implementing the net.Conn interface. This interface utilizes io.Reader and io.Writer, enabling it to be utilized as a conduit for reading and writing. Basic implementations of this interface are provided in the net package as IPConn, UDPConn, and TCPConn types. The appropriate type is returned based on the utilized protocol.

The Dial function facilitates the sending of requests via TCP. An example is shown below:

package main

import (
	"fmt"
	"io"
	"net"
	"os"
)

func main() {
	// Example of sending an HTTP request
	req := "GET / HTTP/1.1\n" +
		"Host: google.com\n\n"

	// Establish a TCP connection to google.com
	tcpConn, err := net.Dial("tcp", "google.com:80")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer tcpConn.Close()

	// Write the HTTP request data to the network
	tcpConn.Write([]byte(req))

	// Like any io.Reader, net.Conn can be used with io.Copy to read data received over the network
	io.Copy(os.Stdout, tcpConn)
}

In this example, an HTTP request represented by the req variable is sent over the network to techiesclues.com. The net.Conn interface allows us to use io.Copy to efficiently read and display the data received over the network, as shown by io.Copy(os.Stdout, tcpConn).

In the aforementioned example, a request to a network resource on the internet is made using the TCP protocol. However, for the same purpose, it is more convenient to utilize the net/http package. This package is explicitly crafted for handling the HTTP protocol, which operates atop the TCP protocol.