Go HTTP

In Go language, under networking, we have http package. The http package provides HTTP server and client implementations.

In this tutorial, we will go through the usage of http package for some of the basic HTTP concepts.

Import http package

To import http package, include the following statement before using any of its methods in a Go program.

</>
Copy
 import "net/http"

HTTP Requests

There are different types of requests that can be make from client to server in Go programming language. They are:

  1. GET
  2. HEAD
  3. POST
  4. POSTFORM

Golang HTTP Get Request

GET request is used to request data from a resource specified by the URI.

In the following example, we make a GET Request to https://www.tutorialkart.com. If there is no error in calling Get() function, we will print the response header.

example.go

</>
Copy
package main

import "fmt"
import "net/http"

func main() {
	resp, err := http.Get("https://www.tutorialkart.com/")
	if err==nil {
		fmt.Println(resp.Header)
	}
	resp.Body.Close()
}

Output

map[Content-Type:[text/html] Server:[Apache/2] Vary:[Accept-Encoding,User-Agent] X-Endurance-Cache-Level:[3] Date:[Thu, 11 Apr 2019 09:22:06 GMT] Keep-Alive:[timeout=30] Connection:[keep-alive] Last-Modified:[Fri, 05 Apr 2019 14:02:59 GMT] Etag:["7526-585c8f1c2e418-gzip"] Accept-Ranges:[bytes] Cache-Control:[max-age=10800] Expires:[Thu, 11 Apr 2019 12:22:06 GMT]]

Note that, when we are done with the response object, close this response object using resp.Body.Close() function.

Conclusion

In this Golang Tutorial, we learned about Go HTTP package, with example programs.